Python 刮板继续爬行相同的链接
我已经用Python 刮板继续爬行相同的链接,python,python-3.x,web-scraping,Python,Python 3.x,Web Scraping,我已经用python和BeautifulSoup编写了一个脚本,使用它的分页按钮(有一个链接连接到这个按钮)进入网站的下一页,直到没有新的页面可抓取为止。我的脚本可以使用分页链接抓取下一页。然而,问题是分页链接永远不会结束,因为按钮(连接到下一页链接)没有变灰,所以我陷入了一个无限循环。我怎样才能以这样的方式摆脱它,这样脚本就会检查我是否连续地删除了两个相同的链接,一旦找到一个,它就会断开 这是我目前的脚本: import requests from bs4 import BeautifulSo
python
和BeautifulSoup
编写了一个脚本,使用它的分页按钮(有一个链接连接到这个按钮)进入网站的下一页
,直到没有新的页面可抓取为止。我的脚本可以使用分页链接抓取下一页。然而,问题是分页链接永远不会结束,因为按钮(连接到下一页链接)没有变灰,所以我陷入了一个无限循环。我怎样才能以这样的方式摆脱它,这样脚本就会检查我是否连续地删除了两个相同的链接,一旦找到一个,它就会断开
这是我目前的脚本:
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
如果我希望采用任何硬编码方法,我本可以避免此类问题,但这不是我的意图。只需存储最后一个链接即可
last_link = link
link = nextpage.get("href")
if link == last_link: break
print(link)