【问题标题】:How to get table headers and table data from a table row together in list?如何从列表中的表格行中获取表格标题和表格数据?
【发布时间】:2019-07-16 02:37:38
【问题描述】:

我正在尝试将表格行中的所有数据放入一个列表中,但其中一些是表头,一些是表格数据,不知道如何同时获取它们。

这适用于使用 bs4 的 Python 3.7

import requests, bs4

url = 'https://www.basketball-reference.com/players/a/abrinal01.html'
res = requests.get(url)
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('#per_game')

table = soup.find("table", { "id" : "per_game" })
table_rows = table.find_all('tr')

for tr in table_rows:
    td = tr.find_all('td')
    row = [i.text for i in td]
    print(row)

我可以将所有表格数据放入一个列表中,因此第一列的所有内容都正确,但第一列中的数据本身却没有。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    要在数据中包含标题,您可以将find_all('td') 的输出与find_all('th') 结合起来。这是你想要的吗?

    import requests, bs4
    
    url = 'https://www.basketball-reference.com/players/a/abrinal01.html'
    res = requests.get(url)
    res.raise_for_status()
    
    soup = bs4.BeautifulSoup(res.text, 'html.parser')
    elems = soup.select('#per_game')
    
    table = soup.find("table", { "id" : "per_game" })
    table_rows = table.find_all('tr')
    
    for tr in table_rows:
        td = tr.find_all('th') + tr.find_all('td')
        row = [i.text for i in td]
        print(row)
    

    产生这个输出:

    ['Season', 'Age', 'Tm', 'Lg', 'Pos', 'G', 'GS', 'MP', 'FG', 'FGA', 'FG%', '3P', '3PA', '3P%', '2P', '2PA', '2P%', 'eFG%', 'FT', 'FTA', 'FT%', 'ORB', 'DRB', 'TRB', 'AST', 'STL', 'BLK', 'TOV', 'PF', 'PTS']
    ['2016-17', '23', 'OKC', 'NBA', 'SG', '68', '6', '15.5', '2.0', '5.0', '.393', '1.4', '3.6', '.381', '0.6', '1.4', '.426', '.531', '0.6', '0.7', '.898', '0.3', '1.0', '1.3', '0.6', '0.5', '0.1', '0.5', '1.7', '6.0']
    ['2017-18', '24', 'OKC', 'NBA', 'SG', '75', '8', '15.1', '1.5', '3.9', '.395', '1.1', '2.9', '.380', '0.4', '0.9', '.443', '.540', '0.5', '0.6', '.848', '0.3', '1.2', '1.5', '0.4', '0.5', '0.1', '0.3', '1.7', '4.7']
    ['2018-19', '25', 'OKC', 'NBA', 'SG', '31', '2', '19.0', '1.8', '5.1', '.357', '1.3', '4.1', '.323', '0.5', '1.0', '.500', '.487', '0.4', '0.4', '.923', '0.2', '1.4', '1.5', '0.6', '0.5', '0.2', '0.5', '1.7', '5.3']
    ['Career', '', '', 'NBA', '', '174', '16', '16.0', '1.8', '4.5', '.387', '1.3', '3.4', '.368', '0.5', '1.1', '.443', '.525', '0.5', '0.6', '.880', '0.3', '1.1', '1.4', '0.5', '0.5', '0.1', '0.4', '1.7', '5.3']
    

    【讨论】:

    • 是的!我只需要将tr.find_all('th') 移到tr.find_all('td') 前面。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多