美丽汤中的css选择器找不到标签

时间:2021-06-06 14:41:09

标签: python html css beautifulsoup

有很多类似的问题,但没有人回答我的问题。我正在尝试使用 CSS 选择器在美丽的汤中找到一个标签。

The specific section of html I am trying to scrape, as the full html is quite large

我抓取的网址在我的代码中。

这里有一些测试代码,希望能说明我的问题:

url = "https://www.basketball-reference.com/boxscores/201510310MEM.html"
response = urlopen(url)
html = response.read().decode()

# proves the element I am selecting exists in the html
print(html.find("table class=\"suppress_all stats_table\" id=\"four_factors\" data-cols-to-freeze=\",1\"")) 

soup = BeautifulSoup(html, 'html.parser')

# this line prints a similar piece of data to the one I want, but not correct
print(soup.select('tbody > tr > td[data-stat="off_rtg"]')[0].get_text())

# when I try being more specific, it prints an empty list
print(soup.select('table[id="four_factors"] tbody > tr > td[data-stat="off_rtg"]'))

输出:

78720
98
[]

正如我的代码所示,可以使用 python 的 String.find() 方法找到的元素由于某种原因对 BeautifulSoup 不可见。我试过使用 BeautifulSoup.find() 和 .findAll() 而不是具有相同结果的 css 选择器。我试过使用 lxml 解析器得到相同的结果。

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为表格位于 HTML 注释 (<!--...-->) 中。

您可以提取表格,检查标签是否为 Comment 类型:

from urllib.request import urlopen
from bs4 import BeautifulSoup, Comment

url = "https://www.basketball-reference.com/boxscores/201510310MEM.html"
response = urlopen(url)
html = response.read().decode()

soup = BeautifulSoup(html, "html.parser")
comments = soup.find_all(text=lambda tag: isinstance(tag, Comment))
comment_soup = BeautifulSoup(str(comments), "html.parser")

print(
    comment_soup.select_one(
        'table[id="four_factors"] tbody > tr > td[data-stat="off_rtg"]'
    ).text
)

输出:

102.5