Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 而用漂亮的汤和蟒蛇做循环_Python_Loops_Beautifulsoup - Fatal编程技术网

Python 而用漂亮的汤和蟒蛇做循环

Python 而用漂亮的汤和蟒蛇做循环,python,loops,beautifulsoup,Python,Loops,Beautifulsoup,好的。现在我真的被难住了。我用BeautifulSoup抓取数据,页面具有结构化格式,例如链接https://www.brightscope.com/ratings/a 收视率通过其他途径进行。评级后的每个字母(如a、b、c等)都有多页。我正在尝试创建一个while循环,以转到每个页面,并且在存在特定条件的情况下,刮除所有我尚未获得该代码的HREF。但是,当我运行代码时,while循环继续不停地运行。如何修复它以转到每个页面并搜索要运行的条件,如果未找到,则转到下一个字母?在任何人询问之前,我已

好的。现在我真的被难住了。我用BeautifulSoup抓取数据,页面具有结构化格式,例如链接https://www.brightscope.com/ratings/a 收视率通过其他途径进行。评级后的每个字母(如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
汤。找“李”是永远不会改变的。在while循环中要做的就是更新变量页面和计数。您需要使用page变量制作一个新的soup,然后它就会改变。也许是这样的

while soup.find('li'):
        page = requests.get(each_rating+str(count))
        soup = BeautifulSoup(page.text, 'html.parser')
        print(page.url)
        count = count+1
        #Keeps running this and never breaks

希望这有助于BeautfulSoup的方法找到第一个孩子。这意味着,如果需要遍历所有元素,则需要使用findAll方法并迭代其结果。

每次计算soup时。查找'li',soup与上次相同,因此它将查找相同的li标记,一次又一次永远。condition soup.find'li'永远不会变为false,因为变量soup在循环中永远不会改变。在count=count+1之后添加行soup=BeautifulSouppage.text,“html.parser”。也许您想要类似于u in soup的内容。查找_all'li':?或者,您也可以存储soup的结果。在变量中查找'li',以便下一次通过时,您可以请求一个li,它是最后一个li的兄弟姐妹,或者类似的内容,但这似乎更复杂。@DYZ为什么重新分析同一页会有帮助?@abarnert它不是同一页。你能给我举个例子吗?不确定你到底想做什么,但可能是这样的。我编辑了原始评论