python - 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")
解决方案
如果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
推荐阅读
- python - 无限期导入 .py 文件
- azure - Azure 空间定位点支持哪些设备?
- php - 试图创建数据库,但我得到这些错误,我不知道是什么
- r - R如何在扩展数据框时在dcast中使用fun.aggregate来保持离散值?
- android-appbarlayout - 迁移项目中的androidx appbarlayout问题
- python - Python堆排序实现解释
- android - 在 onBindViewHolder 中调用 notifyDataSetChanged
- loops - Rust 中是否有与 JavaScript 的 forEach 等价的东西?
- spring - spring.profiles.active 未设置为在命令行上为 Maven 构建指定的配置文件名称
- python - 从 Python Selenium 中的特定标签获取文本