簡體   English   中英

漂亮湯中的 css 選擇器沒有找到標簽

[英]css selector in beautiful soup not finding a tag

有很多類似的問題,但沒有人回答我的問題。 我正在嘗試使用 CSS 選擇器在美麗的湯中找到標簽。

html的具體部分我正在嘗試刮,因為完整的html相當大

我正在抓取的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM