分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

webdriver+expected_conditions二次封装

发布时间:2023-09-06 01:31责任编辑:沈小雨关键词:暂无标签

结合这两种方法对代码做二次封装,可以提升脚本性能

例:

#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二次封装

原文地址:http://www.cnblogs.com/linbao/p/8082254.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved