selenium 判斷元素element是否存在方法


selenium 判斷元素element是否存在方法?

由於selenium本身沒有一個方法檢查元素是否存在。因為為了復用代碼。所以寫一個檢查元素是否存在,來減少因為元素不存在,導致操作元素是報錯。本文主要講兩種判斷元素是否存在方法。

第一種:find_element方法進行判斷

from selenium import webdriver from selenium.common.exceptions import NoSuchElementException browser = webdriver.Chrome(executable_path=r'.\chromedriver.exe', options=options) def is_element_present(by, value):     try:         element = browser.find_element(by=by, value=value)     except NoSuchElementException as e:         return False     return True

第二種:使用延時等待檢查元素是否存在

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Chrome(executable_path=r'.\chromedriver.exe', options=options) def is_element_presen(locator):     wait = WebDriverWait(browser, 8)     try:         wait.until(EC.visibility_of_element_located(locator))     except TimeoutException:         return False     return True


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM