码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-12-11 12:47:03      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:cep   www   val   element   comm   drive   判断   name   class   

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')
# 通过

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

标签:cep   www   val   element   comm   drive   判断   name   class   

原文地址:https://www.cnblogs.com/milesma/p/12021673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!