我在 Python 中使用 Selenium。
在我的腳本中,我撰寫了這一行來檢查是否存在特定元素:
doesElementExist = driver.find_element(By.CSS_SELECTOR,'div.MediaThumbnail.Media--playButton>img').is_displayed()
print(doesElementExist)
為了測驗,我在一個我知道該元素不存在的網站上運行了腳本。因此,我期望 False 作為回傳輸出,因為 is_displayed() 方法回傳一個布林值。
但是,我收到一條錯誤訊息,指出此元素不存在,這會阻止腳本運行,而不是回傳 false 并繼續運行腳本。
Traceback (most recent call last):
File ~/Desktop/ImageScraping/birdsScrapeTest.py:70 in <module>
if driver.find_element(By.CSS_SELECTOR,'div.MediaThumbnail.Media--playButton>img').is_displayed() == True:
File /opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:1251 in find_element
return self.execute(Command.FIND_ELEMENT, {
File /opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:430 in execute
self.error_handler.check_response(response)
File /opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py:247 in check_response
raise exception_class(message, screen, stacktrace)
NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"div.MediaThumbnail.Media--playButton>img"}
知道為什么會這樣嗎?
uj5u.com熱心網友回復:
這不是該is_displayed()方法的作用。此方法將告訴您 是否element可見(隱藏但在 DOM 中)。因此,為了實作您期望的用法,您可以改為:
try:
doesElementExist = driver.find_element(By.CSS_SELECTOR,'div.MediaThumbnail.Media--playButton>img').is_displayed()
except NoSuchElementException:
doesElementExists = False
print("Element doesn't exists")
print(doesElementExist)
無論元素不存在于頁面上還是只是隱藏,此邏輯都應該有效
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478018.html
