beautifulsoup - 我无法使用 for 循环和 BeautifulSoup 从多个 URL 中抓取表数据
问题描述
我正在尝试从多个 URL 中抓取表数据。我要查找的表是特定的,并且在将 .find_all 与 BeautifulSoup 一起使用时,我已将其编入索引。例如,当我在一个 URL 上执行脚本时,它可以正常工作并返回我正在寻找的表。当我使用 for 循环从多个 URL 中抓取表并将它们附加到一个数据帧中时,就会出现问题。
new_table=pd.DataFrame(columns=range(0,10), index=[0])
k=0
for k in range(0, 11200):
response=requests.get(urls[k])
htmls=response.text
soup=BeautifulSoup(htmls, 'html.parser')
table=soup.find_all("table")[4]
row_marker=0
rows=table.find_all("tr")
for row in rows:
column_marker=0
columns=row.find_all("td")
for column in columns:
new_table.iat[row_marker, column_marker]=column.get_text()
column_marker += 1
row_marker += 1
k += 1
new_table
错误:
IndexError Traceback (most recent call last)
<ipython-input-132-13c30de3ad5a> in <module>()
5 soup=BeautifulSoup(htmls, 'html.parser')
6
----> 7 table=soup.find_all("table")[4]
8 row_marker=0
9 rows=table.find_all("tr")
IndexError: list index out of range
解决方案
不设置索引表直接添加检查前
table = soup.find_all("table")
if len(table) < 5:
print('no table[4], skip')
continue
row_marker = 0
rows = table[4].find_all("tr")
推荐阅读
- php - 如何在 prestashop 中初始化一个新的控制器?
- javascript - 然后在承诺解决/拒绝之前执行块(Promise.allSettled)
- stormcrawler - 为什么我们在使用 RDBMS 时,Stormcrawler 中没有用于存储爬取结果的 Bolt?
- javascript - 尽管 JSON.stringify,我的 console.log 返回 [object Object]
- arrays - 当它不是 json 数组时如何使用 ImmutableMappable
- python - 如何在图片中找到透明图标?
- angular - 全局隐藏Angular中的路由
- javascript - 如何从另一个函数触发选择事件 [SAPUI5]
- javascript - Javascript 确认在 Godaddy 中不起作用
- multithreading - 使用 JpaRepository 在指定时间后删除实体