首页 > 解决方案 > 无法使用漂亮的汤选择特定的 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?

标签: pythonweb-scrapingbeautifulsoup

解决方案


您不想使用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

推荐阅读