【问题标题】:Extract just one column of data from HTML table w/ Python?使用 Python 从 HTML 表中仅提取一列数据?
【发布时间】:2015-06-10 07:12:18
【问题描述】:

我正在尝试为我正在做的一个小项目提取一些 NBA 统计数据,我只需要从 HTML 表中提取几列(垂直向上和向下)数据,例如 this one here .我现在只是想获得 PTS,那么我应该如何只提取那一列数据呢?我发现它是每个数据行的倒数第三个元素,但我不确定应该如何解析数据。

【问题讨论】:

    标签: python beautifulsoup html-parsing html-table lxml


    【解决方案1】:

    我建议您阅读整个 html 表格,然后选择您需要的列。也许你会在速度上失去一些东西,但你会在简单性上获得更多。

    用 pandas 的 read_html 函数很容易做到:

    import urllib2
    import pandas as pd
    
    page1 = urllib2.urlopen(
        'http://www.basketball-reference.com/players/h/hardeja01/gamelog/2015/').read()
    
    #Select the correct table by some attributes, in this case id=pgl_basic.
    #The read_html function returns a list of tables.
    #In this case we select the first (and only) table with this id
    stat_table = pd.io.html.read_html(page1,attrs={'id':'pgl_basic'})[0]
    
    #Just select the column we needed. 
    point_column = stat_table['PTS']
    
    print point_column
    

    如果您不熟悉 pandas,可以阅读以下内容: http://pandas-docs.github.io/pandas-docs-travis/10min.html

    例如,您可能希望从表中删除标题行或将表拆分为多个表。

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2020-10-29
      相关资源
      最近更新 更多