【发布时间】:2026-02-05 00:50:01
【问题描述】:
我正在尝试从表中获取信息。但是由于某种原因我不能。我不知道代码中到底缺少什么。在获取另一个表时,相同的代码可以工作(几乎没有更改)。
这是我的代码。
import urllib.request
from bs4 import BeautifulSoup
import pandas as pd
htmlfile = urllib.request.urlopen("https://en.wikipedia.org/wiki/Demographics_of_Finland")
htmltext = htmlfile.read()
soup = BeautifulSoup(htmltext)
all_tables=soup.find_all('table')
right_table=soup.find('table', class_='wikitable')
right_table
#Generate lists
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
H=[]
I=[]
for row in right_table.findAll("tr"):
cells = row.findAll('td')
states=row.findAll('th') #To store second column data
if len(cells)==8: #Only extract table body not heading
A.append(cells[0].find(text=True))
B.append(states[0].find(text=True))
C.append(cells[1].find(text=True))
D.append(cells[2].find(text=True))
E.append(cells[3].find(text=True))
F.append(cells[4].find(text=True))
G.append(cells[5].find(text=True))
H.append(cells[6].find(text=True))
I.append(cells[7].find(text=True))
#import pandas to convert list to data frame
df=pd.DataFrame(A,columns=['Number'])
df['Average´_population_(x 1000)']=B
df['Live_births']=C
df['Deaths']=D
df['Natural_change']=E
df['Crude_birth_rate_(per 1000)']=F
df['>Crude_death_rate_(per_1000)']=G
df['>Natural_change_(per 1000)']=H
df['>Total_fertility_rate']=I
df
【问题讨论】:
-
为什么不直接使用pd.read_html接口BTW?
标签: python pandas beautifulsoup