python selenium基于显示等待封装的一些常用方法
import os
import time
from PIL import Image
from selenium import webdriver
from appium import webdriver as app
from selenium.common.exceptions import *
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from common.logger import Log
from common import read_config def open_browser(browser='chrome'):
"""打开浏览器函数。"firefox"、"chrome"、"ie",'phantomjs'""" # 驱动路径
driver_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
try:
if browser == 'firefox':
executable_path = os.path.join(driver_path, 'driver\\geckodriver.exe')
# executable_path = os.path.join(driver_path, 'driver/geckodriver')
driver = webdriver.Firefox(executable_path=executable_path)
return driver
elif browser == 'chrome':
# 加启动配置,忽略 Chrome正在受到自动软件的控制 提示
option = webdriver.ChromeOptions()
option.add_argument('disable-infobars')
# chrome启动静默模式;默认显示浏览器界面
if read_config.chrome_interface != 'True':
option.add_argument('headless')
executable_path = os.path.join(driver_path, 'driver\\chromedriver.exe')
# executable_path = os.path.join(driver_path, 'driver/chromedriver')
driver = webdriver.Chrome(chrome_options=option, executable_path=executable_path)
return driver
elif browser == 'ie':
driver = webdriver.Ie()
return driver
elif browser == 'js':
driver = webdriver.PhantomJS()
return driver
else:
Log().warning('额,暂不支持此浏览器诶。先试试firefox、chrome、ie、phantomJS浏览器吧。')
return
except Exception as msg:
Log().error('浏览器出错了呀!%s' % msg)
return def open_app():
try:
desired_caps = {
'platformName': read_config.platform_name, 'deviceName': read_config.device_name, 'platformVersion': read_config.platform_version, 'appPackage': read_config.app_package, 'appActivity': read_config.app_activity, 'noReset': True, # 隐藏手机默认键盘
'unicodeKeyboard': True, 'resetKeyboard': True
}
# 关联appium
driver = app.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
return driver
except Exception as e:
raise Exception('连接 Appium 出错:{}'.format(e)) class Crazy:
"""基于原生的selenium框架做二次封装""" def __init__(self, driver):
"""启动浏览器参数化,默认启动chrome"""
self.driver = driver
self.action = ActionChains(self.driver)
self.timeout = 5 # 显示等待超时时间
self.t = 1
self.log = Log() def open(self, url, t=''):
"""get url,最大化浏览器,判断title"""
self.driver.get(url)
self.driver.implicitly_wait(10)
# 是否最大化浏览器
if read_config.maximize != 'True':
self.driver.maximize_window()
try:
WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(t))
self.log.info('打开网页成功!')
except TimeoutException:
self.log.error('打开%s title错误,超时' % url)
except Exception as msg:
self.log.error('打开网页产生的其他错误:%s' % msg) def find_element(self, locator):
"""重写元素定位方法"""
if not isinstance(locator, tuple):
self.log.error('locator参数必须是元组类型,而不是:{}'.format(type(locator)))
return ""
else:
try:
element = WebDriverWait(self.driver, self.timeout, self.t).until(
EC.presence_of_element_located(locator))
if element.is_displayed():
return element
except:
self.log.info('%s页面中未能找到元素%s' % (self, locator))
return "" def find_elements(self, locator):
"""定位一组元素"""
if not isinstance(locator, tuple):
self.log.error('locator参数必须是元组类型,而不是:{}'.format(type(locator)))
return ""
else:
try:
elements = WebDriverWait(self.driver, self.timeout, self.t).until(
EC.presence_of_all_elements_located(locator))
return elements
except:
self.log.info('%s页面中未能找到元素%s' % (self, locator))
return "" def click_coordinate(self, coordinate, timeout=10):
"""点击坐标"""
self.driver.tap(coordinate, timeout) def clicks(self, locator, n):
"""点击一组元组中的一个"""
element = self.find_elements(locator)[n]
element.click() def click(self, locator):
"""点击操作"""
element = self.find_element(locator)
element.click() def double_click(self, locator):
"""双击操作"""
element = self.find_element(locator)
self.action.double_click(element).perform() def send_keys(self, locator, text):
"""发送文本,清空后输入"""
element = self.find_element(locator)
element.clear()
element.send_keys(text) def sends_keys(self, locator, n, text):
"""选中一组元素中的一个,发送文本,清空后输入"""
element = self.find_elements(locator)[n]
element.clear()
element.send_keys(text) def send_keys_enter(self):
"""敲enter"""
self.action.send_keys(Keys.ENTER).perform() def send_keys_down(self):
"""敲向下键"""
self.action.send_keys(Keys.DOWN).perform() def send_keys_arrow_down(self):
self.action.send_keys(Keys.ARROW_DOWN).perform() def send_keys_arrow_right(self):
self.action.send_keys(Keys.ARROW_RIGHT).perform() def is_text_in_element(self, locator, text):
"""判断文本在元素里,没定位到元素返回False,定位到返回判断结果布尔值"""
try:
result = WebDriverWait(self.driver, self.timeout, self.t).until(
EC.text_to_be_present_in_element(locator, text))
self.log.info('is_text_in_element 成功')
return result
except TimeoutException:
self.log.error('%s元素没有定位到' % str(locator))
return False def is_text_in_value(self, locator, value):
"""判断元素的value值,没有定位到返回False,定位到返回判断结果布尔值"""
try:
result = WebDriverWait(self.driver, self.timeout, self.t).until(
EC.text_to_be_present_in_element_value(locator, value))
except TimeoutException:
self.log.error('元素没有定位到:%s' % str(locator))
return False
else:
return result def is_title(self, title):
"""判断title完全等于"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
return result def is_title_contains(self, title):
"""判断title包含"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
return result def is_selected(self, locator):
"""判断元素被选中,返回布尔值, 一般用在下拉框"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_located_to_be_selected(locator))
return result def is_selected_be(self, locator, selected=True):
"""判断元素的状态,selected是期望的参数True/False,返回布尔值"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(
EC.element_located_selection_state_to_be(locator, selected))
return result def is_alert_present(self):
"""判断页面是否有alert,有返回alert,没有返回False"""
result = WebDriverWait(self.driver, self.timeout, self.t).until((EC.alert_is_present()))
text = EC.alert_is_present()(self.driver)
if text:
self.log.info('alert弹框显示文本是:%s' % text.text)
else:
self.log.warning('没有发现alert弹框。')
return result def is_visibility(self, locator):
"""元素可见返回本身,不可见返回False"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.visibility_of_element_located(locator))
return result def is_invisibility(self, locator):
"""元素可见返回本身,不可见返回True,没有找到元素也返回True"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.invisibility_of_element_located(locator))
return result def is_clickAble(self, locator):
"""元素可以点击返回本身,不可点击返回False"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.element_to_be_clickable(locator))
return result def is_locator(self, locator):
"""判断元素有没有被定位到(并不意味着可见),定位到返回element,没有定位到返回False"""
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
return result def move_to_element(self, locator):
"""鼠标悬停操作"""
element = self.find_element(locator)
ActionChains(self.driver).move_to_element(element).perform() def move(self, locator, locator1):
"""循环调用鼠标事件,死循环"""
self.move_to_element(locator)
time.sleep(2)
element = self.find_element(locator1)
self.move_to_element(locator1)
try:
if element.is_displayed:
self.click(locator1)
else:
self.move(locator, locator1)
except ElementNotVisibleException as e:
self.log.error('鼠标点击事件失败:%s' % e) def drag_and_drop(self, element, element1):
"""拖拽"""
ActionChains(self.driver).drag_and_drop(element, element1).perform()
ActionChains(self.driver).click_and_hold(element).release(element1).perform() def switch_frame(self, frame):
"""切换ifarm"""
try:
self.driver.switch_to_frame(self.find_element(frame))
self.log.info('切换iframe成功!')
except:
self.log.warning('没有发现iframe元素%s' % frame) def current_window_handle(self):
"""浏览器handle"""
return self.driver.current_window_handle def switch_window_handle(self, n):
"""切换handle"""
if not isinstance(n, int):
self.driver.switch_to.window(n)
else:
all_handle = self.driver.window_handles
self.driver.switch_to.window(all_handle[n]) def back(self):
"""返回之前的网页"""
self.driver.back() def forward(self):
"""前往下一个网页"""
self.driver.forward() def close(self):
"""关闭当前网页"""
self.driver.close() def quit(self):
"""关闭所有网页"""
self.driver.quit() def get_title(self):
"""获取title"""
return self.driver.title def get_texts(self, locator, n):
"""获取一组相同元素中的指定文本"""
element = self.find_elements(locator)[n]
if element:
return element.text
else:
return None def get_text(self, locator):
"""获取文本"""
element = self.find_element(locator)
if element:
return element.text
else:
return None def get_attribute(self, locator, name):
"""获取属性"""
element = self.find_element(locator)
if element:
return element.get_attribute(name) def js_execute(self, js):
"""执行js"""
return self.driver.execute_script(js) def js_focus_element(self, locator):
"""聚焦元素"""
target = self.find_element(locator)
self.driver.execute_script("arguments[0].scrollIntoView();", target) def js_scroll_top(self):
"""滚动到顶部"""
js = "var q=document.documentElement.scrollTop=0"
self.driver.execute_script(js) def js_scroll_bottom(self):
"""滚动到底部"""
js = "var q=document.documentElement.scrollTop=10000"
self.driver.execute_script(js) def select_by_index(self, locator, index):
"""通过索引,index是第几个,从0开始, 下拉框"""
element = self.find_element(locator)
Select(element).select_by_index(index) def select_by_value(self, locator, value):
"""通过value属性"""
element = self.find_element(locator)
Select(element).select_by_value(value) def select_by_text(self, locator, text):
"""通过text属性"""
element = self.find_element(locator)
Select(element).select_by_visible_text(text) def save_screenshot(self, img_path):
"""获取电脑屏幕截屏"""
self.driver.save_screenshot(img_path) def save_report_html(self):
"""可以在html报告中使用的截图"""
self.driver.get_screenshot_as_base64() def save_element_img(self, locator, img_path):
"""获取元素截图"""
self.driver.save_screenshot(img_path)
element = self.find_element(locator)
left = element.location['x']
top = element.location['y']
right = element.location['x'] + element.size['width']
bottom = element.location['y'] + element.size['height']
im = Image.open(img_path)
im = im.crop((left, top, right, bottom))
im.save(img_path) def get_cookies(self):
"""获取cookies"""
return self.driver.get_cookies() def swipeDown(self, t=500, n=1):
'''向下滑动屏幕'''
l = self.driver.get_window_size()
x1 = l['width'] * 0.5 # x坐标
y1 = l['height'] * 0.25 # 起始y坐标
y2 = l['height'] * 0.75 # 终点y坐标
for i in range(n):
self.driver.swipe(x1, y1, x1, y2, t) def swipeUp(self, t=500, n=1):
'''向上滑动屏幕'''
l = self.driver.get_window_size()
x1 = l['width'] * 0.5 # x坐标
y1 = l['height'] * 0.65 # 起始y坐标
y2 = l['height'] * 0.25 # 终点y坐标
for i in range(n):
self.driver.swipe(x1, y1, x1, y2, t) if __name__ == '__main__':
driver = open_browser()
driver.get('file:///D:/UIAutomation/report/2019-01-15%2017-40-10report.html')
python selenium基于显示等待封装的一些常用方法的更多相关文章
- Python+Selenium自动化-设置等待三种等待方法
Python+Selenium自动化-设置等待三种等待方法 如果遇到使用ajax加载的网页,页面元素可能不是同时加载出来的,这个时候,就需要我们通过设置一个等待条件,等待页面元素加载完成,避免出现 ...
- python selenium 三种等待方式详解[转]
python selenium 三种等待方式详解 引言: 当你觉得你的定位没有问题,但是却直接报了元素不可见,那你就可以考虑是不是因为程序运行太快或者页面加载太慢造成了元素不可见,那就必须要加等待 ...
- selenium的显示等待和隐式等待区别
1.selenium的显示等待 原理:显式等待,就是明确的要等到某个元素的出现或者是某个元素的可点击等条件,等不到,就一直等,除非在规定的时间之内都没找到,那么就跳出Exception.(简而言之:就 ...
- selenium的显示等待、隐式等待
转载:https://www.cnblogs.com/mabingxue/p/10293296.html Selenium显示等待和隐式等待的区别1.selenium的显示等待原理:显示等待,就是明确 ...
- Selenium+Java显示等待和隐式等待
描述:用来操作界面上的等待时间,显示等待是等待某一条件满足,条件满足后进行后面的操作:隐式等待是给出一个等待时间,在时间到达之前若满足条件,则立即执行后续操作. public class TestSe ...
- selenium的显示等待和隐式等待的区别
什么是显示等待和隐式等待?显示等待就是有条件的等待隐式等待就是无条件的等待 隐式等待 当使用了隐式等待执行测试的时候,如果 WebDriver没有在 DOM中找到元素,将继续等待,超出设定时间后则抛出 ...
- Python+Selenium设置元素等待
显式等待 显式等待使 WebdDriver 等待某个条件成立时继续执行,否则在达到最大时长时抛弃超时异常 (TimeoutException). #coding=utf-8 from selenium ...
- Python selenium 三种等待方法
1. 强制等待 sleep(xx) 是最简单粗暴的一种办法,不管你浏览器是否加载完了,程序都得等待3秒,3秒一到,继续执行下面的代码,作为调试很有用,不建议总用这种等待方式,严重影响程序执行速度. 代 ...
- Python+Selenium中级篇之-封装一个自己的类-浏览器引擎类
前一篇文章我们知道了,如何去封装几个简单的Selenium方法到我们自定义的类,这次我们编写一个类,叫浏览器引擎类,通过更改一个字符串的值,利用if语句去判断和控制启动那个浏览器.这里我们暂时,支持三 ...
随机推荐
- abtestingGateway错误集锦
管理接口访问报错 系统版本 内核版本 Ubuntu 14.04.2 3.13.0-32-generic 我们在这里通过curl来插入命令的时候直接报错: curl命令写入规则 curl 'http:/ ...
- Linux环境设置IP及关闭防火墙
确认当前网络配置: [root@localhost ~]# nmcli -p dev ===================== Status of devices ================= ...
- iOS - 提示用户升级版本并跳转到AppStore
一.问题:自己做提示用户升级? 由于苹果做了自动升级,所有只要在应用程序中出现从AppStore检查版本更新,或者出现任何有关升级的提醒都会被拒,但是如果必须添加升级提示的话,可以配合后台通过添加AP ...
- elasticsearch 6.1.1 transport jar
https://files.cnblogs.com/files/xjyggd/transport6.1.1.rar
- C#获取一个数组中的最大值、最小值、平均值
C#获取一个数组中的最大值.最小值.平均值 1.给出一个数组 ,,,,,-,,,,}; 2.数组Array自带方法 本身是直接可以调用Min(),Max(),Average()方法来求出 最小值.最大 ...
- jquery实现同时展示多个tab标签+左右箭头实现来回滚动(美化版增加删除按钮)
闲聊 前段时间小颖分享了:jquery实现同时展示多个tab标签+左右箭头实现来回滚动文章,引入项目后,我们的组长说样子太丑了,小颖觉得还好啊,要不大家评评理,看下丑不丑?无图无真相,来上图: 看吧其 ...
- [原]Jenkins(十六) jenkins再出发之jenkins+robot+blue ocean+svn
jenkins version: 部署省略..(如有需要请查看本博客jenkins系列的文档) 新的jenkins需要先填写administratorpassword (如下图)找到下面红色的路径打开 ...
- gym101808 E
提问:我是什么品种的傻逼? 哇看到积水兴高采烈啊.然后就走上了一条不归路. 为什么不归呢,因为我这个法子就是不对的,我总是在想很多很多点围成的一块区域,然后求这一块区域的面积. 然后尝试了各种扫描方法 ...
- gym 101873
题还没补完 以下是牢骚:删了 现在只有六个...太恐怖了,我发现四星场我连300人的题都不会啊. C:最短路加一维状态就好了叭..嗯,一开始没看到输出的那句话 那个 "."也要输 ...
- 26.webpack 入门
webpack 官方: https://webpack.js.org/ http://webpack.github.io/ 中文: https://www.webpackjs.com/ 资料: htt ...