python-3.x - 使用 BeautifulSoup 从篮球参考中提取表格的问题
问题描述
我想提取具有 id = "all_team-stats-per_game" 的特定表。我正在尝试提取列标题。我能够正确找到具有特定 id 的表,但不确定为什么在搜索标签“tr”时输出为空。代码附在下面。提前致谢。
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
# NBA season we will be analyzing
year = 2019
url = "https://www.basketball-reference.com/leagues/NBA_2019.html"
# this is the HTML from the given URL
html = urlopen(url)
soup = BeautifulSoup(html, features="html.parser")
# use findALL() to get the column headers
# soup.findAll('tr', limit=2)
soup = soup.find(id="all_team-stats-per_game")
print(soup.find_all('th'))
#
# headers = [th.getText() for th in soup[0].findAll('th')]
#
# print(headers)
解决方案
我试图编辑你的代码。我能够找到所需的 div 标签,但里面的表格作为评论被提及,我也使用检查工具对其进行了验证。所以也许这就是它没有获取表格内容的原因
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
# NBA season we will be analyzing
year = 2019
url = "https://www.basketball-reference.com/leagues/NBA_2019.html"
# this is the HTML from the given URL
html = urlopen(url)
soup = BeautifulSoup(html, features="html.parser")
# use findALL() to get the column headers
# soup.findAll('tr', limit=2)
target_div = soup.find("div", {"id": "all_team-stats-per_game"})
print(target_div.prettify())
#
# headers = [th.getText() for th in soup[0].findAll('th')]
#
# print(headers)
推荐阅读
- stored-procedures - 如何在 Entity Framework Core 2.1 中将空参数传递给上下文查询类型
- python - django将变量添加到html标签内的字符串
- ios - 当 UIView 动画时,UIView 中 CALayer 上的动画被取消
- postgresql - postgresql循环函数插入到表中
- c# - IDictionary 如何在删除时获取已删除的项目值
- java - MySQL Connector/J 未将 SQL DATE 转换为 JVM 的时区
- c# - 如何使用 listView c# 对每行的 2 列求和
- sql - 如何最有效地探索一列 url 查询字符串的内容
- playframework-2.5 - java.lang.NoClassDefFoundError : com/google/gson/JsonElement on playframework 在启动服务器时不起作用
- javascript - 使用 XPath 选择包含特定文本的 LI 时遇到问题