首页 > 解决方案 > Web抓取python:IndexError:列表索引超出范围

问题描述

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

回溯(最后一次调用):文件“C:\Users\T947610\Desktop\hahah.py”,第 22 行,在 table = soup.findAll("table", {"class":"display"})[0 ] #Facing error in this statement IndexError: list index out of range

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")

标签: pythonweb-scrapingbeautifulsoupcompiler-errors

解决方案


如果findAllfindall. 我有同样的问题,我使用 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

推荐阅读