我用python创建了一个脚本来解析网页中的不同链接。登录页中有两个部分。一个是Top Experiences
,另一个是More Experiences
。我当前的尝试可以从这两个类别中获取链接。你知道吗
我想收集的链接类型(很少)在Top Experiences
部分下面。但是,当我遍历More Experiences
节下的链接时,我可以看到它们都指向一个页面,其中有一个名为Experiences
的节,在该节下有与登录页Top Experiences
下的链接类似的链接。我要把它们都抓起来。你知道吗
我想要的一个这样的链接是:https://www.airbnb.com/experiences/20712?source=seo
。你知道吗
我当前的尝试从两个类别获取链接:
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
URL = "https://www.airbnb.com/sitemaps/v2/experiences_pdp-L0-0"
def get_links(link):
res = requests.get(link)
soup = BeautifulSoup(res.text,"lxml")
items = [urljoin(link,item.get("href")) for item in soup.select("div[style='margin-top:16px'] a._1f0v6pq")]
return items
if __name__ == '__main__':
for item in get_links(URL):
print(item)
How can I parse all the links under
Top Experiences
section along with the links underExperiences
section that can be found upon traversing the links underMore Experiences
?
如果有任何不清楚的地方,请check out the image。我用了一支油漆笔,所以写起来可能有点难理解。
似乎“顶级体验”和“更多体验”链接共享同一类,因此您可以使用
.find_all
来获取链接。你知道吗重构代码以满足您的编码范式。你知道吗
过程:
获取所有
Top Experiences
链接获取所有
More Experiences
链接向所有
More Experiences
链接逐个发送请求,并获取每个页面Experiences
下的链接。链接所在的
div
是相同的,因为所有页面都具有相同的类_12kw8n71
注意事项:
您所需的链接将出现在三个列表中
top_experiences
、more_experiences
和generated_experiences
我添加了随机延迟以避免被阻塞。
不要打印列表,因为它太长了。你知道吗
top_experiences
-50个链接more_experiences
-299链接generated_experiences
-14950个链接解决方法有点棘手。它可以通过几种方式实现。我发现最有用的是递归地使用
More Experiences
函数中get_links()
下的链接。More Experiences
下的所有链接都有一个公共关键字_pdp-
。你知道吗因此,当您在函数中定义conditional语句以使链接递归地通过函数
get_links()
进行筛选时,else
块将生成所需的链接。最需要注意的是,所有需要的链接都在类_1f0v6pq
中,因此获取链接的逻辑相当简单。你知道吗相关问题 更多 >
编程相关推荐