python - 无法使用漂亮的汤选择特定的 html 元素
问题描述
我试图找到一个嵌套在 all_totals id 中的 tbody 元素(它肯定在那里,我检查过)。
import requests
from bs4 import BeautifulSoup, Comment
url = 'https://www.basketball-reference.com/players/a/abdelal01.html'
data = requests.get(url)
html = BeautifulSoup(data.text, 'html.parser')
print(html.select('#all_totals tbody').prettify())
然而,这个漂亮的汤代码只是返回一个空数组。我认为问题可能是由位于 GIANT html 注释下的所需元素引起的。我添加了一些代码来尝试解析 html 以摆脱评论:
for comment in html.findAll(text=lambda text: isinstance(text, Comment)):
comment.extract()
print(html.select('#all_totals')[0].prettify())
这有助于摆脱评论;但是,嵌套在“all_totals”id 中的大多数(但不是全部)html 在执行此操作后消失了。
我做错了什么,如何正确选择我想要的 html?
解决方案
您不想使用extract
,因为您将删除包含感兴趣的 html 的评论。请参阅以下作为从评论中提取的示例
import pandas as pd
for comment in html.findAll(text=lambda text: isinstance(text, Comment)):
if 'id="totals"' in comment:
table = pd.read_html(comment)[0]
print(table)
break
推荐阅读
- android - 无法通过android中的意图传递数据
- angular - 使用 Angular2 进行翻译
- java - 方法调用 getActivity().getSupportFragmentManager() 可能会在片段中产生空指针异常
- graph - ArangoDB 中优化的推荐引擎
- amazon-web-services - DynamoDB 最终一致性读取 vs 强一致性读取
- mysql - 库存可用性能Mysql
- google-cloud-platform - 统计指定时间内的 GCP 日志条目数
- powershell - 格式化百分比小数位并删除尾随零
- java - 如何在 Java 中将“ConvertText”转换为 ConvertText?
- python - Python 从 GPIO 追加一次仅列出一个数据