selenium 判断元素element是否存在方法
2019年10月7日 15:52 4554 人阅读 2 条评论 编辑
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