Python Beautiful Soup 列表手动工作,但对于for循环却不起作用?

2024-05-06 02:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有问题,使用漂亮的汤。我在下面的代码中得到这个错误消息,当我手动将数字放入列表索引(例如:c=b[11])时,它工作了,但是当我将代码附加到for循环并使用c=b[I]时,代码就不工作了。“b”中有220个链接,我想要每11个链接。当我手动输入c=b[0](<;—页面上的第一个链接)和c=b[209](<;—页面上的最后一个/第20个链接)时,它们都能工作,只是当我将其置于for循环下时,它不工作

a = urlopen(url) # Opens the page that I want

for i in range(0, 220, 11): # Once the url is open, gets the 20 links on the page
        bsobj = BeautifulSoup(a, "lxml")
        b = bsobj.findAll("td", height="10") #len of b is 220
        c = b[i] #len is 1
        d = c.findAll("a")
        e = d[0].attrs["href"]
        f = e[13:18]

Traceback (most recent call last):
  File "C:\Users\Perl\Documents\Finviz.py", line 48, in <module>
    c = b[i] #len is 1
IndexError: list index out of range

Tags: the代码inlturlforlenis