提问者:小点点

Web scraping Python:indexerror:列表索引超出范围


脚本从文本文件读取单个URL,然后从该web页面导入信息并将其存储在CSV文件中。 该脚本适用于单个URL。 问题:我在我的文本文件中逐行添加了几个URL,现在我希望我的脚本读取第一个URL,做所需的操作,然后回到文本文件读取第二个URL并重复。 一旦我添加了for循环来完成此操作,我声明将面临以下错误:

Traceback(最近的最后调用):文件“C:\users\T947610\desktop\hahah.py”,第22行,in table=soup.findAll(“table”,{“class”:“display”})[0]#faring error in this语句indexerror:列表索引超出范围

f = open("URL.txt", 'r')
for line in f.readlines():
    print (line)
    page = requests.get(line)
    print(page.status_code)
    print(page.content)
    soup = BeautifulSoup(page.text, 'html.parser')
    print("soup command worked")
    table = soup.findAll("table", {"class":"display"})[0] #Facing error in this statement
    rows = table.findAll("tr")

共2个答案

匿名用户

如果单个url输入可以工作,那么问题可能是从。txt中添加新的输入行。 尝试将。strip()应用到该行,该行的头部和尾部通常有空格

page = requests.get(line.strip())

另外,如果soup.findAll()什么也没有找到,它将返回None,这是无法索引的。 试着打印汤,检查内容。

匿名用户

Kunjal,有时如果findall在findall中找不到数据,它会抛出一个异常。 我也遇到了同样的问题,我使用try/except来解决这个问题,只是您需要处理的空值可能与前面所述的不同,例如:

f = open("URL.txt", 'r')
for line in f.readlines():
    print (line)
    page = requests.get(line)
    print(page.status_code)
    print(page.content)
    soup = BeautifulSoup(page.text, 'html.parser')
    print("soup command worked")
    try:
      table = soup.findAll("table", {"class":"display"})[0] #Facing error in this statement
      rows = table.findAll("tr")
    except IndexError:
       table = None
       rows = None