python - 如何从列表中的表格行中获取表格标题和表格数据?
问题描述
我正在尝试将表格行中的所有数据放入一个列表中,但其中一些是表格标题,其中一些是表格数据,不确定如何同时获取它们。
这适用于使用 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)
我可以将所有表格数据放入一个列表中,因此第一列的所有内容都正确,但第一列中的数据本身不正确。
解决方案
要在数据中包含标题,您可以结合find_all('td')
with 的输出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']
推荐阅读
- firebase - Firestore,startAfter 和 startAfterDocument 的区别
- python - QuantLib 中 FixedRateBond 的 exCoupon 期限
- flutter - 第一次双击时未触发 onDoubleTap
- java - 将 ObservableList 绑定到 TreeTableView 项
- javascript - JS:找到下一个可用游戏的天数的有效算法
- .htaccess - 将所有 URls 重定向到文件夹内的文件,即使 URL 为空
- flutter - Flutter web 404在apache上没有哈希没有htaccess
- javascript - 缩小页面混乱对齐
- bash - for 循环遍历序列,然后创建字符串并通过 json 发布
- python - 在没有 OAuth 和 API 密钥的情况下获取 Youtube 分析