python - 用漂亮的汤和蟒蛇循环
问题描述
好吧。现在我真的很难过。我正在用漂亮的汤刮数据,并且页面具有结构化格式,例如链接是https://www.brightscope.com/ratings/a
评级通过的other
。评级后的每个字母(例如 a、b、c、...)都有多个页面。我正在尝试创建一个while循环来访问每个页面,并且在存在特定条件时抓取所有href(我还没有得到那个代码)。但是,当我运行代码时,while 循环会继续不停地运行。如何修复它以转到每个页面并搜索要运行的条件,然后如果找不到,请转到下一个字母?li
在任何人可能会问之前,我已经搜索了代码并且在它继续运行时没有看到任何标签。
例如:https://www.brightscope.com/ratings/A/18
是 A 的最高值,但它会继续运行。
import requests
from bs4 import BeautifulSoup
url = "https://www.brightscope.com/ratings/"
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
hrefs = []
ratings = []
ks = []
pages_scrape = []
for href in soup.findAll('a'):
if 'href' in href.attrs:
hrefs.append(href.attrs['href'])
for good_ratings in hrefs:
if good_ratings.startswith('/ratings/'):
ratings.append(url[:-9]+good_ratings)
del ratings[0]
del ratings[27:]
count = 1
# So it runs each letter a, b, c, ...
for each_rating in ratings:
#Pulls the page
page = requests.get(each_rating)
#Does its soup thing
soup = BeautifulSoup(page.text, 'html.parser')
#Supposed to stay in A, B, C,... until it can't find the 'li' tag
while soup.find('li'):
page = requests.get(each_rating+str(count))
print(page.url)
count = count+1
#Keeps running this and never breaks
else:
count = 1
break
解决方案
BeautfulSoup 的find()
方法找到第一个孩子。这意味着,如果您需要遍历所有<li>
元素,则需要使用 findAll() 方法并迭代其结果。