![](/img/trans.png)
[英]Using Python (Selenium) to Scrape IMDB (.click() is not working)
[英]Scrape IMDB reviews and rating using Selenium
我正在嘗試抓取 IMDB 上特定電影的評論和評級信息。 這是我的抓取評級代碼:
try:
rating = review.find_element_by_css_selector('[class = "rating-other-user-rating"]')
star_rating.append(rating.text)
except:
rating = None
這是HTML
<span class="rating-other-user-rating">
<svg class="ipl-icon ipl-star-icon " xmlns="http://www.w3.org/2000/svg" fill="#000000" height="24" viewBox="0 0 24 24" width="24">
<path d="M0 0h24v24H0z" fill="none"></path>
<path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
<span>7</span><span class="point-scale">/10</span>
</span>
問題:
我需要從上面的 HTML 中檢索“7”。我在檢索它的代碼中缺少什么。 我認為問題在於評級位於沒有類或 ID 的 span 標簽中,我還想不通,非常感謝您的幫助。 謝謝
我怎樣才能從 IMDB 中抓取一定數量的評論? 例如,如果我只想抓取 50 條評論。 我嘗試使用下面的代碼,但這不起作用。 程序繼續執行並且不會在 50 處停止:
nextbutton = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.CLASS_NAME,'ipl- load-more__button'))) if len(movie_title) == 50: # movie_title is the number of reviews titles scraped so far. 50 is ideal break nextbutton.click()
你已經足夠接近了。 評分7在<span>
內並且是其祖先<span>
的第二個后代
<span class="rating-other-user-rating">
<svg class="ipl-icon ipl-star-icon " xmlns="http://www.w3.org/2000/svg" fill="#000000" height="24" viewBox="0 0 24 24" width="24">
<path d="M0 0h24v24H0z" fill="none"></path>
<path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"></path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
<span>7</span>
<span class="point-scale">/10</span>
</span>
要理想地提取文本7 ,您需要為visibility_of_element_located()引入WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR和文本屬性:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.rating-other-user-rating span:first-of-type"))).text)
使用XPATH和get_attribute("innerHTML")
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='rating-other-user-rating']//span[not(@class)]"))).get_attribute("innerHTML"))
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在How to retrieve the text of a WebElement using Selenium - Python中找到相關討論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.