[英]css selector in beautiful soup not finding a tag
有很多类似的问题,但没有人回答我的问题。 我正在尝试使用 CSS 选择器在美丽的汤中找到标签。
我正在抓取的 url 在我的代码中。
这是一些测试代码,希望能显示我的问题:
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"]'))
Output:
78720
98
[]
正如我的代码所示,可以使用 python 的 String.find() 方法找到的元素由于某种原因对 BeautifulSoup 不可见。 我尝试使用 BeautifulSoup.find() 和 .findAll() 而不是 css 选择器,结果相同。 我试过使用 lxml 解析器,结果相同。
发生这种情况是因为该表位于 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
)
Output:
102.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.