使用webdriverwait封裝查找元素方法


對於selenium原生的查找元素方法進行封裝,在timeout規定時間內循環查找頁面上有沒有某個元素

這樣封裝的好處:

1.可以有效提高查找元素的效率,避免元素還沒加載完就拋異常

2.相對於time.sleep和implictly_wait更節省時間

3.大大的減少重復代碼,使得用例書寫更簡潔

代碼:

#coding:utf-8

#封裝元素方法
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *
import time
class Base():
def __init__(self,driver):
self.driver=driver

#查找元素
def find_element(self,locator):#locator參數是定位方式,如("id", "kw"),把兩個參數合並為一個 ,*號是把兩個參數分開傳值
element=WebDriverWait(self.driver,20,0.5).until(lambda x:x.find_element(*locator))
return element
#判斷元素是否存在
def is_exists(self,locator):
try:
WebDriverWait(self.driver,20,0.5).until(lambda x:x.find_element(*locator))
return True
except:
return False
#判斷元素是否已經不存在,不存在了返回True,還存在就返回False
def element_is_disappeared(self,locator,timeout=30):
is_disappeared=WebDriverWait(self.driver,timeout,1,(ElementNotVisibleException)).until_not(lambda x:x.find_element(*locator).is_displayed())
print is_disappeared

#封裝一個send_keys
def send_keys(self,locator,text):
self.find_element(locator).send_keys(text)

#封裝一個click
def click(self,locator):
self.find_element(locator).click()

#運行主函數
if __name__=='__main__':
driver=webdriver.Chrome()
driver.get("https://www.baidu.com")
#實例化
base=Base(driver)
#定位輸入框
input_loc=("id","kw")
#通過實例調用find_element來發送
base.send_keys(input_loc,"selenium")
#點擊按鈕
button_loc=("id","su")
base.click(button_loc)

time.sleep(3)
driver.quit()

*可根據實際情況編寫方法


免責聲明!

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



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