【问题标题】:css selector in beautiful soup not finding a tag漂亮汤中的css选择器找不到标签
【发布时间】:2021-08-23 20:51:17
【问题描述】:

有很多类似的问题,但没有人回答我的问题。我正在尝试使用 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 解析器,结果相同。

【问题讨论】:

  • 请提供您正在抓取的 html 的链接(例如使用 pastebin)而不是图片,这样可以更轻松地进行测试:)
  • 我可以试试,但是如果您需要完整的 html,您不能直接转到代码中的链接,右键单击,然后选择检查吗? @Seon
  • 我的错,我读得很快,错过了链接。

标签: python html css beautifulsoup


【解决方案1】:

发生这种情况是因为该表位于 HTML cmets (<!--...-->) 内。

您可以提取表格检查标签是否为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

【讨论】:

  • 这成功了!但我有几个问题: 1. 我在页面的 html 中找到了 cmets 内的表格版本,但我也找到了任何 cmets 之外的版本。您可以在我的帖子中的图片中看到任何 cmets 之外的版本。如果它在 cmets 内,突出显示将是绿色的,对吗? 2. 如果表格在cmets里面,为什么会出现在网页上?
  • 页面由js渲染。所以它作为 cmets 的源 html,然后运行 ​​javascript 来创建您在网站上看到的表格。
猜你喜欢
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多