当前位置:首页 > Web开发 > 正文

webdriver中判断元素是否存在的方法

2024-03-31 Web开发

selenium.webdriver中没有内置的判断元素是否存在的方法,所以定义一个方法,如果找到该元素则返回True,否则返回False:

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException class Demo: def __init__(self): # 初始化 self.driver = webdriver.Chrome() #实例化 self.driver.get('') #打开指定网址 def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException: return False return True <html> <head> </head> <body> <a href='' id='id_01' class='class_01' name='name_01' >这是一个链接</a> </body> </html> #通过id is_element_present(By.ID,'id_01') #通过name is_element_present(By.NAME,'name_01') # 通过class_name is_element_present(By.CLASS_NAME,'class_01') # 通过tag_name is_element_present(By.TAG_NAME,'a') # 通过

webdriver中判断元素是否存在的方法

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/40812.html