【问题标题】:Index Out Of Range When Seems to Exist似乎存在时索引超出范围
【发布时间】:2021-10-17 17:17:52
【问题描述】:

全新的程序员。

尝试使用下面的类来抓取特定方面。 There are 5 in total 在检查窗口中。当我尝试打印第三个索引时,它给了我一个“超出范围”的错误。有什么线索吗?

import bs4
from bs4 import BeautifulSoup
import requests
import lxml

vegas_insider = requests.get('https://www.vegasinsider.com/college-football/matchups/', 'r').text
soup = BeautifulSoup(vegas_insider, 'lxml')

closing_line = soup.find('td', class_ = 'viCellBg2 cellBorderL1 cellTextNorm padCenter').text[2]

print(float(closing_line))

【问题讨论】:

    标签: python python-3.x web-scraping indexing


    【解决方案1】:

    find() 只返回一个元素,即它找到的第一个元素。 如果您想要所有带有特定标签的元素,则必须改用find_all()

    https://beautiful-soup-4.readthedocs.io/en/latest/index.html?highlight=find#find

    【讨论】:

    • 如果我想在特定类中找到第三个元素怎么办?我不想要第一个,也不想要所有的。但介于两者之间。
    • 然后从返回的数组中获取第三个元素find_all()[2]
    • 谢谢。我有 .text[2] 而不是 [2].text 它就是这样工作的。感谢您的帮助!!!
    • 别担心,如果您也接受答案,将不胜感激:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    相关资源
    最近更新 更多