【问题标题】:Is there a better solution for this?? Python Pandas BeautifulSoup有没有更好的解决方案? Python Pandas BeautifulSoup
【发布时间】: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


    【解决方案1】:

    不知道你所说的“更好”是什么意思,但你可以使用列表推导来让它更 Pythonic:

    h = [th.get_text().split("\n")[0] for th in ths]

    可以替换您的第一个循环。也许你可以看看你是否可以用类似的东西替换你的第二个循环。

    【讨论】:

      【解决方案2】:

      您可以尝试使用pandas.read_html(),让他们进行网页抓取:

      import pandas as pd
      
      dfs = pd.read_html('https://de.wikipedia.org/wiki/Liste_der_Hochschulen_in_Deutschland')
      df = dfs[0] # select the first table read
      

      【讨论】:

      • 第一部分代码效果很好,但我不太明白第二部分。
      • 对此感到抱歉 - 我从您的代码中认为您可能只是试图用相同的列初始化一个空数据框。但为了清楚起见,我会删除。
      猜你喜欢
      • 1970-01-01
      • 2015-02-04
      • 2021-08-24
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多