我用python编写了一个scraper,它使用BeautifulSoup库来解析遍历网站不同页面的所有名称。我可以管理它,如果不是一个以上的网址不同的分页,这意味着有些网址有分页,有些没有,因为内容很少。在
我的问题是:如何在一个函数中编译它们来处理它们是否分页?在
我最初的尝试(它只能解析每个url的第一页的内容):
import requests
from bs4 import BeautifulSoup
urls = {
'https://www.mobilehome.net/mobile-home-park-directory/maine/all',
'https://www.mobilehome.net/mobile-home-park-directory/rhode-island/all',
'https://www.mobilehome.net/mobile-home-park-directory/new-hampshire/all',
'https://www.mobilehome.net/mobile-home-park-directory/vermont/all'
}
def get_names(link):
r = requests.get(link)
soup = BeautifulSoup(r.text,"lxml")
for items in soup.select("td[class='table-row-price']"):
name = items.select_one("h2 a").text
print(name)
if __name__ == '__main__':
for url in urls:
get_names(url)
如果有一个具有如下分页的url,我本可以完成整个过程:
^{pr2}$但是,所有的url都没有分页。那么,我怎样才能把它们都抓到,不管有没有分页?在
看来我找到了解决这个问题的一个非常有效的方法。这种方法是迭代的。它将首先检查该页面中是否有可用的
next page
url。如果找到一个,它将跟踪该url并重复该过程。但是,如果任何链接没有分页,则scraper将中断并尝试另一个链接。在这里是:
此解决方案尝试查找分页
a
标记。如果找到任何分页,则当用户在类PageScraper
的实例上迭代时,将刮取所有页面。否则,将只对第一个结果(单个页面)进行爬网:类的构造函数将找到任何分页,并且
^{pr2}$__iter__
方法只在找到分页链接的情况下保存所有页面。例如,https://www.mobilehome.net/mobile-home-park-directory/rhode-island/all没有分页。因此:但是,第一页的内容可以找到:
但是,对于分页完整的页面,所有生成的页面都可以被刮掉:
PageScraper.feed_link
将自动完成此检查,并输出第一页,如果找到分页,则输出所有后续结果,如果结果中不存在分页,则只输出第一页:相关问题 更多 >
编程相关推荐