对于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()
*可根据实际情况编写方法
使用webdriverwait封装查找元素方法
原文地址:http://www.cnblogs.com/linbao/p/8081598.html