【发布时间】:2021-10-11 12:26:50
【问题描述】:
我很好奇我是否有最简单的方法。 我想从 wikipedia 中抓取一个表格并将其传输到 pandas 数据框 (https://de.wikipedia.org/wiki/Liste_der_Hochschulen_in_Deutschland)。
from bs4 import BeautifulSoup as bs
import pandas as pd
import requests
r = requests.get("https://de.wikipedia.org/wiki/Liste_der_Hochschulen_in_Deutschland")
soup = bs(r.content)
table = soup.find("table")
ths = table.find_all("th")
h = []
headers = []
for th in ths:
th = th.get_text().split("\n")[0]
h.append(th)
for th in h:
th = th.split("- ")
if len(th) > 1:
th = th[0] + th[1]
else:
th = th[0]
headers.append(th)
df = pd.DataFrame(columns = headers)
它有效(我得到了一个带有正确列名的df),但我认为必须有更好的方法。
这里是“ths”列表,所以你不必运行所有这些。
</th>,
<th>Land
</th>,
<th>Form
</th>,
<th>Träger
</th>,
<th>Promotions-<br/> recht
</th>,
<th>Grün-<br/> dung
</th>,
<th>Studierende
</th>,
<th>Stand
</th>]
【问题讨论】:
标签: python pandas list dataframe beautifulsoup