该部分的 HTML 为:
<div class="review-small-text">
<span class="stars-rate">
<span property="starsRating">
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
<i class="fa fa-star-yellow fa-star"></i>
</span>
</span>
<span property="reviewRating" typeof="Rating" style="display:none;">
<span property="ratingValue">5</span>
<span property="bestRating">5</span>
<span property="worstRating">0</span>
</span>
<span property="itemReviewed" typeof="Service" class="">Liposuction</span> </div>
我正在尝试使用 selenium 提取特定评论的第二个跨度 ratingValue,并且我尝试使用此 css 选择器提取该值:
'div.review-small-text>span:nth-of-type(2)>span:nth-of-type(1)'
但它给了我一个空字符串。 也尝试过这个
'div.review-small-text>span:nth-child(2)>span:nth-child(1)'
所以我认为问题不在于CSS选择器。显示无在这里会产生问题。 有没有可能的方法来提取该值?
到目前为止我尝试过的Python源代码是:
from selenium import webdriver
import time
url = "myurlhere"
driver = webdriver.Chrome()
driver.get(url)
time.sleep(3)
all_reviews_listings = driver.find_elements_by_xpath("//div[@id='tab_reviews']/div[@class='provider_all_Reviews']/div[@id='pnlReviews']/div")
for review in all_reviews_listings:
review_rating = review.find_element_by_css_selector('div.review-small-text>span:nth-of-type(2)>span:nth-of-type(1)').text
print("Review Rating: ", review_rating)
最佳答案
这是获取 ratingValue 的 css。
使用 JavaScript:
review_rating = driver.execute_script("""return document.querySelector(".review-small-text > span[property='reviewRating'] > span[property='ratingValue']").textContent""")
没有 JavaScript:您也可以这样做。
driver.find_element_by_css_selector(".review-small-text > span:nth-child(2) > span[property='ratingValue']").get_attribute("textContent")
关于javascript - 如何从属性 style="display :none; 的元素中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55874700/