我是新来美丽的汤和嵌套表,因此我尝试获得一些经验刮维基百科表。美丽的汤维基百科嵌套表
我在网上搜索了很好的例子,但不幸的是我还没有找到任何东西。
我的目标是通过这张web page,通过熊猫解析“美利坚合众国的国家”表格。正如你从我的代码下面可以看到我有以下问题:
1)我不能提取所有的列。显然,我的代码不允许在pandas DataFrame中正确导入所有列,并将第一列下方的html表格的第三列条目写入。
2)我不知道如何处理colspan =“2”它出现在表格的某些行中。在我的熊猫DataFrame中,我想在资本和最大城市相同的情况下拥有相同的条目。
这是我的代码。请注意,我试图克服我的第一个问题。
代码:
from urllib.request import urlopen
import pandas as pd
wiki='https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'
page = urlopen(wiki)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page)
right_table=soup.find_all('table')[0] # First table
rows = right_table.find_all('tr')[2:]
A=[]
B=[]
C=[]
D=[]
F=[]
for row in rows:
cells = row.findAll('td')
# print(len(cells))
if len(cells)>=11: #Only extract table body not heading
A.append(cells[0].find(text=True))
B.append(cells[1].find(text=True))
C.append(cells[2].find(text=True))
D.append(cells[3].find(text=True))
F.append(cells[4].find(text=True))
df=pd.DataFrame(A,columns=['State'])
df['Capital']=B
df['Largest']=C
df['Statehood']=D
df['Population']=F
df
print(df)
你有任何suggestings? 任何帮助理解更好的BeautifulSoup将不胜感激。 在此先感谢。
的清洁版维基百科的那些表是人类FYI编辑。这意味着他们往往是一团糟。 – pguardiario