Skip to main content
 首页 » 编程设计

python之(Python 3, BeautifulSoup 4)之在 Div 中抓取分页

2025年05月04日13bjzhanghao

我可以抓取这个网站的第一页:

http://ratings.food.gov.uk/enhanced-search/en-GB/%5E/London/Relevance/0/%5E/%5E/0/1/10

但我试图通过使用网站分页中的“下一步”按钮来抓取网站上的所有其他页面。

我单击了“下一步”按钮,我可以看到第 2 页的参数从 0/1/10 更改为 0/2/10,依此类推。

我查看了分页代码,我可以看到分页在一个 Div 中

 <div id="pagingNext" class="link-wrapper"> 

问题是我只成功地使用下面的代码从另一个站点抓取了分页:

button_next = soup.find("a", {"class": "btn paging-next"}, href=True) 
while button_next: 
    time.sleep(2)#delay time requests are sent so we don't get kicked by server 
    soup=makesoup(url = "https://www.propertypal.com{0}".format(button_next["href"])) 

这行得通,但是由于我目前正在抓取的这个网站似乎没有为下一个按钮 URL 提供 href,所以我不知道如何尝试抓取它

我试过:

button_next = soup.find("div", {"class": "paging-Next"}) 
while button_next: 
    time.sleep(2)#delay time requests are sent so we don't get kicked by server 
    soup=makesoup(url = "https://www.propertypal.com{0}".format(button_next)) 

但它似乎并没有抓取其他页面,只是第一页还在。

如果有人能提供帮助,我将不胜感激。

谢谢

请您参考如下方法:

无需验证 button_next url,因为您已经知道 url 在所有页面中的变化方式。因此,我建议不要使用 url“http://ratings.food.gov.uk/enhanced-search/en-GB/%5E/London/Relevance/0/%5E/%5E/0/1/10”,而是使用“http://ratings.food.gov.uk/enhanced-search/en-GB/%5E/London/Relevance/0/%5E/%5E/0/1/50”,该网站提供了一次查看 50 个项目的选项,因此您无需遍历 4044,而只需浏览 809 页。

在 while 循环中,我们等待 current 为 810,所以我们知道最后一页被抓取了,因为通过检查,/809/50 是最后一页.

import requests 
from bs4 import BeautifulSoup 
 
current = 0 
while current < 810:  # Last page, by inspection is /809/50 
    url = "http://ratings.food.gov.uk/enhanced-search/en-GB/%5E/London/Relevance/0/%5E/%5E/0/{:d}/50".format(current) 
    data = requests.get(url).text  
    soup = BeautifulSoup(data, "html.parser") 
    print(url) 
    current += 1 
    #  Do your scraping here