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


免責聲明!

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



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