【发布时间】:2020-09-02 10:48:10
【问题描述】:
我正在尝试使用 beautifulsoup 和请求从以下站点抓取表格数据: https://www.worldometers.info/world-population/
我在运行代码时遇到这种错误:
> Traceback (most recent call last): File
> "d:\python\population\worldpop.py", line 16, in <dictcomp>
> result=[{ header[index]:cells.text for index,cells in enumerate(row.find_all('td'))} for row in rows_data] IndexError:
> list index out of range
当然,我知道在访问超出范围的项目时会发生这种类型的错误,但是对于这个特定的问题,我遇到了麻烦。 我期待这个问题的适当解决方案。
#worknig 从 worldometers.info 抓取表格数据并将其转换为 csv 文件。
from bs4 import BeautifulSoup
import requests
import pandas
url='https://www.worldometers.info/world-population/'
def world_population():
page=requests.get(url)
soup=BeautifulSoup(page.content,'html.parser')
pop_data=soup.find('table', class_='table table-striped table-bordered table-hover table-condensed
table-list')
header=[heading.text for heading in pop_data.find_all('th')]
#print(header)
rows_data=[row for row in pop_data.find_all('tr')]
result=[{ header[index]:cells.text for index,cells in enumerate(row.find_all('td'))} for row in
rows_data]
df=pandas.DataFrame(result)
df.to_csv('pop.csv')
world_population()
【问题讨论】:
-
你要去哪张桌子?
标签: python-3.x pandas web-scraping beautifulsoup python-requests