我必须通过从维基百科文章中的表中创建一堆列表来创建python中的数据框架。
代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv
import pandas as pd
import numpy as np
url = "https://en.wikipedia.org/wiki/Texas_Killing_Fields"
page = urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
all_tables = soup.find_all('table')
all_sortable_tables = soup.find_all('table', class_='wikitable sortable')
right_table = all_sortable_tables
A = []
B = []
C = []
D = []
E = []
for row in right_table.find_all('tr'):
cells = row.find_all('td')
if len(cells) == 5:
row.strip('n')
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))
E.append(cells[4].find(text=True))
df = pd.DataFrame(A, columns=['Victim'])
df['Victim'] = A
df['Age'] = B
df['Residence'] = C
df['Last Seen'] = D
df['Discovered'] = E
我一直得到一个属性错误"ResultSet对象没有属性'find_all'。您可能将元素列表视为单个元素。当你想调用find()时,你调用了find_all()吗?">
我试过很多方法,但都无济于事。我还按照老师给我们的教程,它也没有帮助。
教程:https://alanhylands.com/how-to-web-scrape-wikipedia-python-urllib-beautiful-soup-pandas/标题- 10. -循环- -行
第一次作为提问者来到这里。
备注:正如@ggorlen所提到的,使用现有的api将是最好的方法。我还建议使用更结构化的方法来存储数据,以避免这些列表。
data = []
for row in soup.select('table.wikitable.sortable tr:has(td)'):
data.append(
dict(
zip([h.text.strip() for h in soup.select('table.wikitable.sortable tr th')[:5]],
[c.text.strip() for c in row.select('td')][:5])
)
)
pd.DataFrame(data)
只是使用pandas.read_html()
抓取表的另一种方法,因为您已经导入了pandas
。它还使用BeautifulSoup
并为您完成工作:
import pandas as pd
df = pd.read_html('https://en.wikipedia.org/wiki/Texas_Killing_Fields')[1]
df.iloc[:,:5] ### displays only the first 5 columns as in your example
输出: