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

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('http://www.demo.com')  #打开指定网址

    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='http://www.baidu.com' 
        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')
# 通过
posted @ 2019-12-11 11:53  MilesMa  阅读(3720)  评论(0编辑  收藏  举报