【发布时间】:2018-06-22 22:04:16
【问题描述】:
我已经在python 和BeautifulSoup 中编写了一个脚本,以使用它的分页按钮(有一个链接到该按钮)进入网站的next page,直到没有新页面爬行。我的脚本可以使用分页链接抓取next pages。但是,问题是分页链接永远不会结束,因为按钮(连接到下一页链接)没有变灰,所以我陷入了无限循环。我怎样才能以这种方式摆脱它,以便脚本检查我是否正在同时抓取两个相同的链接,并且一旦找到它就会中断。
到目前为止,这是我的脚本:
import requests
from bs4 import BeautifulSoup
def get_content(link):
while True:
res = requests.get(link)
soup = BeautifulSoup(res.text, 'lxml')
#some code here to do the rest of the activity
nextpage = soup.select_one(".roundright a")
if not nextpage:break #The loop doesn't break because the next page button never grayes out
link = nextpage.get("href")
print(link)
if __name__ == '__main__':
url = "http://www.viprealestateug.com/action/rentals/"
get_content(url)
它产生的结果:
http://www.viprealestateug.com/action/rentals/page/2/
http://www.viprealestateug.com/action/rentals/page/3/
http://www.viprealestateug.com/action/rentals/page/4/
http://www.viprealestateug.com/action/rentals/page/4/
http://www.viprealestateug.com/action/rentals/page/4/
and so on
如果我希望采用任何硬编码方法,我本可以避免这些问题,但这不是我的意图。
【问题讨论】:
标签: python python-3.x web-scraping