1. 程式人生 > >webdriver+expected_conditions二次封裝

webdriver+expected_conditions二次封裝

timeout out 函數 fin 方式 quit exists self. sts

結合這兩種方法對代碼做二次封裝,可以提升腳本性能

例:

#coding:utf-8

#封裝元素方法
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import *
from selenium.webdriver.support import expected_conditions as EC
import time
#加入下面三行代碼 在python2中就不會出現亂碼問題
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8‘)

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))
print(element)
return element
#判斷元素文本
def is_text_in_element(self,locator,text):
try:
WebDriverWait(self.driver,20,0.5).until(EC.text_to_be_present_in_element(locator,text))
return True
except TimeoutException:
return False
#判斷元素的value屬性
def is_value_element(self,locator,text):
try:
WebDriverWait(self.driver,20,0.5).until(EC.text_to_be_present_in_element_value(locator,text))
return True
except:
return False

#判斷元素是否被定位到
def is_exists(self,locator):
try:
WebDriverWait(self.driver,20,0.5).until(EC.presence_of_element_located(locator))#不需要*,這裏跟*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()
# #封裝一個text
# def get_text(self,locator,text):
# return self.find_element(locator,text).text

#運行主函數
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=("css selector","#su")
base.click(button)
print base.is_text_in_element(("link text", "地圖"), "地圖")
time.sleep(3)
driver.quit()

webdriver+expected_conditions二次封裝