首页 > 解决方案 > 我无法使用 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

标签: beautifulsoupindex-error

解决方案


不设置索引表直接添加检查前

table = soup.find_all("table")
if len(table) < 5:
    print('no table[4], skip')
    continue
row_marker = 0
rows = table[4].find_all("tr")

推荐阅读