【问题标题】:Use Pandas to Get Multiple Tables From Webpage使用 Pandas 从网页中获取多个表
【发布时间】:2017-02-14 11:39:28
【问题描述】:

我正在使用 Pandas 解析来自以下页面的数据:http://kenpom.com/index.php?y=2014

为了获取数据,我在写:

dfs = pd.read_html(url) 

数据看起来很棒并且解析得很好,除了它只从前 40 行中获取数据。这似乎是表格分离的问题,这使得熊猫无法获得所有信息。

如何让 pandas 从该网页上的所有表格中获取所有数据?

【问题讨论】:

    标签: python pandas web-scraping html-parsing


    【解决方案1】:

    您发布的页面的 HTML 有多个 <thead><tbody> 标签,这混淆了 pandas.read_html

    按照这个SO thread你可以手动unwrap这些标签:

    import urllib
    from bs4 import BeautifulSoup
    
    html_table = urllib.request.urlopen(url).read()
    
    # fix HTML
    soup = BeautifulSoup(html_table, "html.parser")
    # warn! id ratings-table is your page specific
    for table in soup.findChildren(attrs={'id': 'ratings-table'}): 
        for c in table.children:
            if c.name in ['tbody', 'thead']:
                c.unwrap()
    
    df = pd.read_html(str(soup), flavor="bs4")
    len(df[0])
    

    返回369

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多