【问题标题】:How can I extract a table from wikipedia using Beautiful soup如何使用美丽的汤从维基百科中提取表格
【发布时间】:2020-10-24 13:06:41
【问题描述】:

我正在尝试编写一个从this wikipedia 页面中提取表格的刮板。问题是,我可以提取页面上的所有表格,除了我实际需要的表格(这是包含所有统计信息的表格曾经在美国进行过的选举)。我不认为问题出在我的标签上。
这是我的代码

from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
from urllib.request import urlopen

#getting the wiki page
page_info=urlopen('https://en.wikipedia.org/wiki/United_States_presidential_election')

soup=BeautifulSoup(page_info, 'html.parser')

headline=soup.find('table', "wikitable sortable jquery-tablesorter")
print(headline)

我认为我缺少一些重要的东西,但我无法理解它。谁能帮帮我。

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup urllib


    【解决方案1】:

    这样做的一种方法是:

    import pandas as pd
    import requests
    from bs4 import BeautifulSoup
    
    
    page = requests.get('https://en.wikipedia.org/wiki/United_States_presidential_election').text
    soup = BeautifulSoup(page, 'html.parser')
    table = soup.find('table', class_="wikitable sortable")
    
    df = pd.read_html(str(table))
    df = pd.concat(df)
    print(df)
    df.to_csv("elections.csv", index=False)
    
    

    哪些输出:

         Year                                    Party  ... Electoral votes      Notes
    0    1788                              Independent  ...        69 / 138        NaN
    1    1788                               Federalist  ...        34 / 138        NaN
    2    1788                               Federalist  ...         9 / 138        NaN
    3    1788                               Federalist  ...         6 / 138        NaN
    4    1788                               Federalist  ...         6 / 138        NaN
    ..    ...                                      ...  ...             ...        ...
    [219 rows x 8 columns]
    

    或者像这样的.csv 文件:

    注意:无论何时进行抓取,请始终关闭 JS (JavaScript)。 BeautifulSoup 看不到动态呈现的内容。这样你就不会得到任何回报,因为没有JS,你所追求的标签的类是不同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      相关资源
      最近更新 更多