该部分的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>
我正在尝试使用硒来提取特定评论的第二跨度的 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-selector中。在此显示均不显示问题。 是否有可能提取该值?
到目前为止,我尝试过的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)
答案 0 :(得分:1)
这是获取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")
答案 1 :(得分:0)
祖先标签的属性为style="display:none;
,因此要提取所有 reviewRatings ,您可以使用以下解决方案:
driver.execute_script("arguments[0].removeAttribute('style')", driver.find_element_by_css_selector("div.review-small-text span[property='reviewRating'][typeof='Rating']"))
print([element.text for element in driver.find_elements_css_selector("div.review-small-text span[property='reviewRating'][typeof='Rating'] span")])