簡體   English   中英

如何從具有屬性style =“ display:none;的元素中提取文本;

[英]How to extract text from element with attribute style="display:none;

該部分的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)

這是獲取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")

祖先標簽的屬性為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")])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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