python+selenium十:selenium的二次封装

python+selenium十:基于原生selenium的二次封装

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
# BY的用法
# driver.find_element("id", "kw")
# driver.find_element(By.ID, "kw")

class Bace():
'''基于原生的selenium做二次封装'''

def __init__(self, driver:webdriver.Firefox): # driver:webdriver.Firefox:映射driver 为webdriver.Firefox
self.driver = driver
self.timeout = 10
self.t = 0.5

def find(self, locator, value=''):
''' 定位到元素,返回元素对象,没定位到,Timeout异常 loctor 传元祖,如("id", "kw") '''
if not isinstance(locator, tuple):
print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")')
else:
print(f"正在定位元素信息:定位方式->{locator[0]}, 元素值->{locator[1]},value值->{value}")
if value != '': # value值定位
ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
return ele
else: # 默认为此常规定位方法
ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
if ele:
return ele
else:
print(f"定位失败:定位方式->{locator[0]}, value值->{locator[1]}")
return False

def finds(self, locator, value=''):
''' 定位到元素,返回元素对象,没定位到,Timeout异常 loctor 传元祖,如("id", "kw") '''
if not isinstance(locator, tuple):
print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")')
else:
print(f"正在定位元素信息:定位方式->{locator[0]}, 元素值->{locator[1]},value值->{value}")
if value != '': # value值定位
eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
return eles
else: # 默认为此常规定位方法
eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
if eles:
return eles
else:
print(f"定位失败:定位方式->{locator[0]}, value值->{locator[1]}")
return []

def sendKeys(self, locator, text):
try:
self.find(locator).send_keys(text)
except:
print(f"输入 {text} 失败")

def click(self, locator):
try:
self.find(locator).click()
except:
print("点击失败")

def clear(self, locator):
try:
self.find(locator).clear()
except:
print("清空内容失败")

def isSelected(self, locator, Type=''):
''' 判断元素是否被选中,返回bool值 及点(选中/取消选中)'''
ele = self.find(locator)
try:
if Type == '': # 如果type参数为空,返回元素是否为选中状态,True/False (默认)
r = ele.is_selected()
return r
elif Type == 'click': # 如果type参数为click,执行元素的点击操作
ele.click()
else:
print(f"type参数 {Type} 错误,仅可为click或''")
except:
return False

def isElementExist(self, locator):
''' 判断单个元素是否在DOM里面 (是否存在)'''
try:
self.find(locator)
return True
except:
return False

def isElementExists(self, locator):
''' 判断一组元素是否在DOM里面 (是否存在),若不存在,返回一个空的list'''
eles = self.finds(locator)
n = len(eles)
if n == 0:
return False
elif n == 1:
return True
else:
print(f"定位到元素的个数:{n}")
return True

def title(self, title, Type='contains'):
''' 根据传入的type类型判断title '''
try:
if Type == 'is': # 判断当前网页title名为title 返回bool值
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
return result
elif Type == 'contains': # 判断当前网页title名含title 返回bool值 (默认)
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
return result
else:
print(f"type参数 {Type} 错误,仅可为is、contains")
except:
return False

def in_element(self, locator, value, Type='text'):
''' 根据传入的type判断内容是否在指定元素里面 '''
if not isinstance(locator, tuple):
print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")')
try:
if Type == 'text': # 判断当前获取到的text含value 返回bool值 (默认)
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, value))
return result
elif Type == 'value': # 判断当前获取到的value含value 返回bool值, value为空字符串,返回False
result = self.find(locator, value)
return result
else:
print(f"type参数 {Type} 错误,仅可使用text或value属性定位")
return False
except:
return False

def alert(self, timeout=3, Type=''):
''' 根据传入的type判断alert弹窗及操作 '''
result = WebDriverWait(self.driver, timeout, self.t).until(EC.alert_is_present())
try:
if Type == '': # 判断alert是否存在,如果有,就返回alert对象 (默认)
if result:
return result
else:
print("alert不存在")
return False
elif Type == 'yes': # 执行alert的确定按钮
result.accept()
elif Type == 'no': # 执行alert的取消按钮
result.dismiss()
else:
print(f"type参数 {Type} 错误,仅可为yes、no、或''")
except:
return False

def get(self, locator, Type='text', name=''):
''' 根据传入的type判断获取指定的内容 (title、text、attribute)
type==attribute: 获取元素属性 name:属性 className、name、text、value··· '''
try:
if Type == 'title': # 获取当前网页 title
return self.driver.title
elif Type == 'text': # 获取元素文本值(默认)
return self.find(locator).text
elif Type == 'attribute': # 获取当前元素属性
return self.find(locator).get_attribute(name)
else:
print(f"给的type参数 {Type} 错误,仅可用title、text、attribute")
except:
print(f"获取 {Type} 值失败")
return ''

def select(self, locator, value, Type='index'):
''' 下拉选项框 根据传入的type值判断(index、value、text) '''
element = self.find(locator) # 定位select这一栏
try:
if Type == 'index': # 用下标选择 (默认)
Select(element).select_by_index(value)
elif Type == 'value': # 根据value值选择
Select(element).select_by_value(value)
elif Type == 'text': # 根据选项的文本内容选择
Select(element).select_by_visible_text(value)
else:
print(f"给的type参数 {Type} 错误,仅可为:int、text、value")
except:
print(f"根据 {value} 操作下拉框失败")

def iframe(self, id_index_locator):
''' 常规切换 iframe'''
try:
if isinstance(id_index_locator, int): # 如果传入的是数字,则以该数字为下标取值
self.driver.switch_to.frame(id_index_locator)
elif isinstance(id_index_locator, str): # 如果传入的是字符串,则用iframe名字取值
self.driver.switch_to.frame(id_index_locator)
elif isinstance(id_index_locator, tuple): # 如果是元祖,则根据传入的locator取值
ele = self.find(id_index_locator)
self.driver.switch_to.frame(ele)
except:
print("iframe切换异常")

def handle(self, value):
''' 句柄切换,index、句柄名 '''
try:
if isinstance(value, int): # 切换到该下标对应的窗口
handles = driver.window_handles
self.driver.switch_to.window(handles[value])
elif isinstance(value, str): # 切换到该句柄名称对应的窗口
self.driver.switch_to.window(value)
else:
print(f"传入的type参数 {value} 错误,仅可传int、str")
except:
print(f"根据 {value} 获取句柄失败")

def move_to_element(self, locator):
''' 鼠标悬停操作 '''
try:
ele = self.find(locator)
ActionChains(self.driver).move_to_element(ele).perform()
except:
print("鼠标悬停操作失败")
return False
'''==============================js与jQuery相关====================================='''

def js_focus_element(self, locator):
''' 聚焦元素 '''
target = self.find(locator)
self.driver.execute_script("arguments[0].scrollIntoView();", target)

def js_scroll_top(self):
''' 滚动到顶部 '''
js = "window.scrollTo(0,0)"
self.driver.execute_script(js)

def js_scroll_end(self, x=0):
''' 滚动到底部 '''
js = f"window.scrollTo({x},document.body.scrollHeight)"
self.driver.execute_script(js)

def js_find(self, action):
''' js查找元素,并做相应操作(默认id属性) 输入值:value='XXX' 点击:click() '''
js = f"document.getElementById(“id”).{action}"
self.driver.execute_script(js)

def js_finds(self, Type, element, index, action):
''' js查找元素,并做相应操作 输入值:value='XXX' 点击:click()
js定位仅可为:id、Name、TagName、ClassName、Selector(CSS) '''
list = ['Name', 'TagName', 'ClassName', 'Selector']
if type in list:
print(f"正在执行js操作:定位方式->{Type}, 元素值->{element}, 下标值->{index}, 执行操作->{action}")
if type == 'Selector':
js = f'document.query{Type}All("{element}"){index}.{action}'
else:
js = f'document.getElementsBy{Type}({element})[{index}].{action};'
self.driver.execute_script(js)
else:
print(f"type参数 {Type} 错误,js定位仅可为:'Name'、'TagName'、'ClassName'、'Selector'(CSS)")

def js_readonly(self, idElement, value):
''' 去掉只读属性,并输入内容 一般为id '''
js = f'document.getElementById({idElement}).removeAttribute("readonly");document.getElementById({idElement}).value="{value}"'
driver.execute_script(js)

def js_iframe(self, Type, element, action, index=''):
''' Js处理iframe 无需先切换到iframe上,再切回来操作
输入值:value='' 点击:click() type=id时,index='' '''
js = f'document.getElementBy{Type}({element}){index}.contentWindow.document.body.{action}'
driver.execute_script(js)
'''
jquery = '$(CSS).val("XXX");' # 根据css语法定位到元素,输入内容
jquery = '$(CSS).val('');' # 清空
jquery = '$(CSS).click();' # 点击
driver.execute_script(jquery)
'''

# def switch_alert(self):
# ''' 获取alert弹窗 '''
# r = self.is_alert()
# if not r:
# print("alert不存在")
# else:
# return r

# def is_title(self, title):
# '''判断当前title名为title 返回bool值'''
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
# return result
# except:
# return False
# def is_title_contains(self, title):
# '''判断当前title名含title 返回bool值'''
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
# return result
# except:
# return False

# def is_text_in_element(self, locator, _text=''):
# '''判断当前获取到的text含_text='' 返回bool值'''
# if not isinstance(locator, tuple):
# print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")')
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, _text))
# return result
# except:
# return False
# def is_value_in_element(self, locator, _value=''):
# '''返回bool值, value为空字符串,返回False'''
# if not isinstance(locator, tuple):
# print('locator参数类型错误,必须传元祖类型:loc = ("id", "value1")')
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, _value))
# return result
# except:
# return False

# def get_title(self):
# '''获取title'''
# return self.driver.title
# def get_text(self, locator):
# '''获取文本'''
# try:
# t = self.find(locator).text
# return t
# except:
# print("获取text失败,返回'' ")
# return ""
# def get_attribute(self, locator, name):
# '''获取属性'''
# try:
# element = self.find(locator)
# return element.get_attribute(name)
# except:
# print("获取%s属性失败,返回'' "%name)
# return ""

# def select_by_index(self, locator, index=0):
# '''通过索引,index是索引第几个,从0开始,默认选第一个'''
# element = self.find(locator) # 定位select这一栏
# Select(element).select_by_index(index)

# def select_by_value(self, locator, value):
# '''通过value属性'''
# element = self.find(locator)
# Select(element).select_by_value(value)

# def select_by_text(self, locator, text):
# '''通过文本值定位'''
# element = self.find(locator)
# Select(element).select_by_visible_text(text)

# def switch_handle_window_name(self, window_name):
# ''' 根据句柄名字切换句柄 '''
# self.driver.switch_to.window(window_name)
# def switch_handle_index(self, index):
# ''' 根据句柄下标切换句柄 '''
# handles = driver.window_handles
# self.driver.switch_to.window(handles[index])

# def js_find(self, action):
# '''
# 输入值:value='XXX' 点击:click()
# '''
# print("正在执行js操作,操作行为:%s"%action)
# js = "document.getElementById(“id”).%s"%action
# self.driver.execute_script(js)

if __name__ == "__main__":
driver = webdriver.Firefox()
driver.get("")
zentao = Base(driver)
# loc1 = (By.ID, "account")
# loc2 = (By.CSS_SELECTOR, "[name='password']")
# loc3 = (By.XPATH, "//*[@id='submit']")

loc1 = ("id", "account")
loc2 = ("css selector", "[name='password']")
loc3 = ("xpath", "//*[@id='submit']")
zentao.sendKeys(loc2, 123)

zentao.move_to_element(loc3)

转载于:https://www.cnblogs.com/dwdw/p/9998660.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/450598.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

TDD开发模式实现代码功能逻辑(自己总结,持续更新)

1.先写测试 2.要使程序尽快的通过(及早交付) 3.优化程序结构,尽量使程序尽量快的运行 4.不要怕修改,单元测试会保证接口的正常运行 5.能通过测试后再去重构(消除冗余,优化程序设计) 6.用尽…

Intellij IDEA Debug调试技巧

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 1、这里以一个web工程为例,点击图中按钮开始运行web工程。 2、设置断点 3、使用postman发送http请求 4、请求发送之后会自动…

15行代码让苹果设备崩溃,最新的iOS 12也无法幸免

安全研究人员Sabri Haddouche发现了一个只需几行代码就可以让iPhone崩溃并重启的方法。\\Sabri Haddouche在GitHub上发布了一个示例网页,只有15行代码,如果在iPhone或iPad上访问这个页面,就会崩溃并重启。在macOS上使用Safari打开该页面也会出…

appium更新到1.8.2,不能打开运行的解决办法

1、更新下载appium 1.8.2 打开运行 一直是这个界面。很烦躁,重启电脑或者卸载后重新安装还是没有用。 解决版本: 1、查看老版本和新版本的安装位置 老版本默认是 C:\Program Files (x86)/appium安装新的版本后,地址是:C:\Users…

C语言运算符及其优先级汇总表口诀

C语言运算符及其优先级汇总表口诀圆下箭头一顿号非凡增减富强针地长三乘除,四加减,五移位千万别把鱼忘记,它在盛饭的厨子里小灯大灯灯灯不等爸喂鱼,舅疑惑,裸鸡也疑惑十三姨,十四父,十五逗&…

laraval如何使用tdd

1.首先新建一个laravel birdboard项目 composer create-project --prefer-dist birdboard 2.新建单元测试 php artisan make:test ProjectTest 3.书写单元测试 对于初学着来说,最好先预测tdd即将要出现的错误,然后进行测试,判断是否和自…

让你页面速度飞起来 Web前端性能优化

百度网盘下载 第1章 课程简介对课程做简单的介绍。第2章 资源合并与压缩通过本章,我们学习和理解了web前端的概念,以及性能优化的意义所在,并且通过实战中的压缩与合并,深入理解了减少http请求数和减少http请求资源大小两个优化要…

spring-data-JPA使用JpaRepository注解自定义SQL查询数据库多表查询

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。 一. 首先在Entity注解的类里面要写好外键关系. 这个 ManyToOne 注解可以建立外键关系, 不要在自己傻傻的写一个 private int grades_id…

工厂示例

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Reflection;namespace Common.DALFactory {/// <summary>/// 数据层对象实例创建/// </summary>public partial class DbFacto…

手把手教你如何优化C语言程序

程序进行优化&#xff0c;通常是指优化程序代码或程序执行速度。优化代码和优化速度实际上是一个予盾的统一&#xff0c;一般是优化了代码的尺寸&#xff0c;就会带来执行时间的增加&#xff0c;如果优化了程序的执行速度&#xff0c;通常会带来代码增加的副作用&#xff0c;很…

posman使用教程

1.新建文件夹 2.新建请求&#xff0c;右击文件夹&#xff0c; 3.点开测试文件&#xff0c;有get,put,post方法&#xff0c;我经常使用的是put方法&#xff0c;区别我就不讲了 4.我基本上填在body里面 5.这是基本的使用&#xff0c;我来更高级一点添加环境变量&#xff0c;一共有…

Linux实战教学笔记42:squid代理与缓存实践(一)

第1章 Squid介绍 1.1 缓存服务器介绍 缓存服务器&#xff08;英文意思cache server&#xff09;,即用来存储&#xff08;介质为内存及硬盘&#xff09;用户访问的网页&#xff0c;图片&#xff0c;文件等等信息的专用服务器。这种服务器不仅可以使用户可以最快的得到他们想要的…

Mysql中DATE_SUB 使用方法结合查询一天内,一周内,一月内的信息实例讲解

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 在对数据查询或菜单时经常要对指定的时间或时间段进行查询,例如要查询一天内的信息,要查询一周内的信息,要查询一个月内的,南昌网站建设公…

mac电脑php中安装swoole扩展件

1.首先更新php版本&#xff0c;如果已经是最新的请忽略&#xff0c; &#xff08;1&#xff09;查看是否安装php brew search php &#xff08;2&#xff09;安装最新版本php brew install php 2.查看是否安装openssl&#xff0c;安装了请忽略 &#xff08;1&#xff09;查看…

再谈C语言指针—指向另一指针的指针

一、回顾指针概念 早在本书第贰篇中我就对指针的实质进行了阐述。今天我们又要学习一个叫做“指向另一指针地址”的指针。让我们先回顾一下指针的概念吧&#xff01;当我们程序如下声明变量&#xff1a;short int i;char a;short int * pi;程序会在内存某地址空间上为各变量开辟…

Java练习 SDUT-1586_计算组合数

计算组合数 Time Limit: 1000 ms Memory Limit: 32768 KiB Problem Description 计算组合数。C(n,m),表示从n个数中选择m个的组合数。 计算公式如下&#xff1a; 若&#xff1a;m0&#xff0c;C(n,m)1 否则&#xff0c; 若 n1&#xff0c;C(n,m)1 否则&#xff0c;若mn&#xf…

mysql日期时间操作函数详解

前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到教程。 win7可以设定每周从哪一天开始&#xff0c;win2003等不能方便的修改。有的是周日开始&#xff0c;有的是周一开始。而工作中有的时候每周…

对C语言进行调试的最好方法是什么?

要了解调试程序的最好方法&#xff0c;首先要分析一下调试过程的三个要素&#xff1a;应该用什么工具调试一个程序?用什么办法才能找出程序中的错误?怎样才能从一开始就避免错误?应该用什么工具调试一个程序?有经验的程序员会使用许多工具来帮助调试程序&#xff0c;包括一…

如何赋值hook定义的变量

1、定义变量 const { tableProps, mutate} useRequest(async (params {}) > {const { success, data, total } await Api.getUserAccountApi({page: params.current || 1,...searchValue,});return {list: success ? data : [],total: success ? total : 0,};},{pagin…

java中的sleep()和wait()的区别

对于sleep()方法&#xff0c;我们首先要知道该方法是属于Thread类中的。而wait()方法&#xff0c;则是属于Object类中的。sleep()方法导致了程序暂停执行指定的时间&#xff0c;让出cpu该其他线程&#xff0c;但是他的监控状态依然保持者&#xff0c;当指定的时间到了又会自动恢…