一、selenium常用方法封装(baseselenium.py)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import os
from Common.log_utils import LogUtils
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import pyperclip
import allure
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
class driver():
# 调用浏览器,可以考虑写到conftest.py
def open_browser(self, browser_type):
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
if browser_type == 'chrome':
driver = webdriver.Chrome(options=options)
return driver
elif browser_type == 'firefox':
driver = webdriver.firefox()
else:
print('type error')
class BaseSelenium(object):
def __init__(self, driver):
"""WebDriver需以参数的形式传入,否则运行时会导致多个浏览器窗口被打开"""
self.driver = driver
"""log类实例化"""
self.log = LogUtils()
# 调用浏览器
def open_browser(self, browser_type):
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
if browser_type == 'chrome':
driver = webdriver.Chrome(options=options)
return driver
elif browser_type == 'firefox':
driver = webdriver.firefox()
else:
print('type error')
#关闭浏览器
def quit(self):
self.driver.quit()
"传入URL,最大化窗口"
def open_url(self, url):
self.driver.maximize_window()
self.url = "https://%s" % url
self.driver.get(self.url)
"获取title"
def get_title(self):
self.log.info("获取页面title")
try:
self.log.info("当前页面title为:{}".format(self.driver.title))
return self.driver.title
except Exception as e:
self.log.error("获取页面title失败{}".format(e))
self.screenshot_save()
"获取页面元素"
def get_element(self, *args):
sleep_time = 10
frequency = 0.5
if args is not None:
try:
# 显式等待,等待元素可见
element = WebDriverWait(self.driver, sleep_time, frequency).until(
EC.visibility_of_element_located(*args)
)
except Exception as e:
self.log.error("查找元素{}失败:{}".format(args, e))
else:
return element
else:
self.log.error("element value is NUll")
def get_elements(self, *args):
sleep_time = 10
frequency = 0.5
if args is not None:
try:
# 显式等待,等待元素可见
elements = WebDriverWait(self.driver, sleep_time, frequency).until(
EC.visibility_of_all_elements_located(*args)
)
except Exception as e:
self.screenshot_save()
self.log.error("查找元素{}失败:{}".format(args, e))
else:
return elements
else:
self.log.error("element value is NUll")
"获取页面元素"
def get_element_presence(self, *args):
sleep_time = 10
frequency = 0.5
if args != None:
try:
# 显式等待,等待元素存在
element = WebDriverWait(self.driver, sleep_time, frequency).until(
EC.presence_of_element_located(*args)
)
except Exception as e:
self.screenshot_save()
self.log.error("查找元素{}失败:{}".format(*args, e))
else:
return element
else:
self.log.error("element value is NUll")
"等待元素可点击"
def element_clickable(self, *args):
sleep_time = 10
frequency = 0.5
if args != None:
try:
# 显式等待,等待元素可点击
element = WebDriverWait(self.driver, sleep_time, frequency).until(
EC.element_to_be_clickable(*args)
)
if element:
return element
else:
self.screenshot_save()
except Exception as e:
self.screenshot_save()
self.log.error("查找元素{}失败:{}".format(args, e))
else:
self.log.error("element value is NUll")
def click_clickable(self, name=None, *args):
try:
element = self.get_element(*args)
print(element)
element.click()
except Exception as e:
self.screenshot_save()
self.log.error("{}元素[{}]点击失败".format(name, e))
else:
self.log.info("点击{},元素[{}]点击成功".format(name, *args))
"模拟键盘输入方法重写"
def send_key(self, value, *args):
if args is not None:
if value is not None and value != 'None':
try:
element = self.get_element(*args)
element.send_keys(str(value))
self.log.info("输入值:{}".format(value))
except:
try:
element = self.get_element_presence(*args)
element.send_keys(str(value))
self.log.info("二次尝试输入值:{}".format(value))
except Exception as e:
self.log.error("输入错误:{}{}".format(value, e))
self.screenshot_save()
else:
self.log.warning("没有传入字符串,或输入为空")
else:
self.log.error("没有传入元素")
"重写清空输入框方法"
def clear_value(self, *args):
if args is not None:
try:
element = self.get_element(*args)
element.clear()
self.log.info("清除输入框{}成功".format(*args))
except Exception as e:
self.log.error("清除输入框{}失败".format(e))
self.screenshot_save()
else:
self.log.error("没有传入元素")
"重写模拟鼠标悬停方法"
def mouse_move(self, *args):
try:
action = self.get_element_presence(*args)
ActionChains(self.driver).move_to_element(action).perform()
self.log.info("鼠标移动到元素{}成功".format(*args))
except Exception as e:
self.log.error("鼠标移动至元素:{}失败".format(e))
self.screenshot_save()
def double_click(self, name, *args):
if args:
try:
ele = self.get_element(*args)
ActionChains(self.driver).double_click(ele).perform()
self.log.info("双击{}成功".format(name))
except Exception as e:
self.log.error('双击元素{}失败{}:'.format(args, e))
self.screenshot_save()
else:
self.log.error('传入元素为空')
"重写表单提交方法"
def text_submit(self, *args):
try:
ele = self.get_element(*args)
ele.submit()
self.log.info("表单{}提交成功".format(*args))
except Exception as e:
self.log.error("表单{}提交失败".format(e))
self.screenshot_save()
"重写页面文字获取方法"
def get_text(self, *args):
try:
text = self.get_element(*args).text
self.log.info("获取文字 {} 成功".format(text))
return text
except Exception as e:
self.log.error("获取文字失败!{},尝试二次获取".format(e))
try:
text = self.get_element_presence(*args).text
self.log.info("获取文字 {} 成功".format(text))
return text
except Exception as e:
self.log.error("二次获取文字失败!{}".format(e))
self.screenshot_save()
"多元素文字匹配"
def get_texts(self, *args):
text = []
try:
for ele in self.get_elements(*args):
text.append(ele.text)
except Exception as e:
self.log.error("获取文字失败!{}".format(e))
self.screenshot_save()
else:
self.log.info("获取文字 {} 成功".format(text))
return text
"重写页面截图方法"
def screenshot_save(self, name=None):
p = os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep ) #xxx路径
path=p+r'\xxx\Outputs\logs'
# print(path)
if name:
try:
file_path = os.path.join(path, name +
time.strftime("%Y.%m.%d-%H-%M-%S") + '.png')
self.driver.save_screenshot(file_path)
allure.attach(file_path, name, allure.attachment_type.PNG)
self.log.info("页面[{}]截图成功".format(self.get_url()))
except Exception as e:
self.log.error("截图失败{}".format(e))
else:
try:
file_path = os.path.join(path,
time.strftime("%Y.%m.%d-%H-%M-%S") + '.png')
self.driver.save_screenshot(file_path)
self.log.info("页面[{}]截图成功".format(self.get_url()))
except Exception as e:
self.log.error("截图失败{}".format(e))
"重写获取当前页面URL方法"
def get_url(self):
url = self.driver.current_url
if url:
try:
self.log.info("获取URL[{}]成功".format(url))
return url
except Exception as e:
self.log.error("获取URL失败{}".format(e))
else:
self.log.error("获取url失败")
"重写点击元素方法"
def click_element(self, name=None, *args):
try:
element = self.get_element(*args)
element.click()
self.log.info("点击{},元素[{}]点击成功".format(name, *args))
except Exception as e:
self.log.error("{}元素[{}]第一次点击失败".format(name, e))
try:
self.log.info('切换到元素存在')
self.element_presence_click(name, *args)
except Exception as e:
self.log.error("{}元素[{}]第二次点击失败".format(name, e))
self.screenshot_save()
try:
self.log.info('切换到js点击')
self.js_click(name, *args)
except Exception as e:
self.log.error("{}元素[{}]第三次点击失败".format(name, e))
self.screenshot_save()
# 获取元素值
def get_attribute(self, name, *args):
try:
attribute = self.get_element(*args).get_attribute(name)
if attribute:
self.log.info("获取元素{}成功:{}".format(name, attribute))
return attribute
except Exception as e:
self.log.warning(e)
self.screenshot_save(name)
# 模拟回车方法
def keys_enter(self, *args):
try:
ele = self.get_element(*args)
ele.send_keys(Keys.ENTER)
self.log.info("元素{}回车成功".format(args))
except Exception as e:
self.log.error("模拟回车失败,原因:{}".format(e))
self.screenshot_save()
# 模拟输入框全选删除
def keys_delete(self, *args):
try:
ele = self.get_element(*args)
ele.send_keys(Keys.CONTROL + "a")
ele.send_keys(Keys.BACKSPACE)
except Exception as e:
self.log.error("删除失败{}".format(e))
self.screenshot_save()
# 获取剪切板信息
def get_paste(self, *args):
try:
ele = self.get_element(*args)
ele.send_keys(Keys.CONTROL + "a")
ele.send_keys(Keys.CONTROL + "c")
vls = pyperclip.paste()
self.log.info("获取剪切板信息成功:{}".format(vls))
return vls
except Exception as e:
self.log.error("获取剪切板失败:{}".format(e))
# 删除html属性
def remove_art(self, js_path, art_name):
js = '{}.removeAttribute("{}");'.format(js_path, art_name)
try:
self.driver.execute_script(js)
self.log.info('运行删除{}属性js脚本成功'.format(art_name))
except Exception as e:
self.log.error('运行删除#{}#js脚本失败{}'.format(art_name, e))
# 通过js点击
def js_click(self, name, *args):
element = self.get_element(*args)
try:
self.driver.execute_script("arguments[0].click();", element)
self.log.info('点击{}成功'.format(name))
except Exception as e:
self.log.error('通过js点击{}元素{}失败'.format(name, e))
def js_get_text(self, *args):
element = self.get_element_presence(*args)
try:
res = self.driver.execute_script("arguments[0].getInnerHTML();", element)
self.log.info('获取{}成功'.format(res))
except Exception as e:
self.log.error('通过js获取{}元素{}失败'.format(*args, e))
else:
return res
# 使用selenium默认的点击
def default_click(self, name, args):
try:
element = self.driver.find_element(*args)
element.click()
except Exception as e:
self.log.error('元素{}点击失败:{}'.format(*args, e))
else:
self.log.info('不加任何等待,直接点击:{}'.format(name))
# 等待元素存在时点击
def element_presence_click(self, name, *args):
try:
element = self.get_element_presence(*args)
element.click()
except Exception as e:
self.log.error("点击{}元素[{}]点击失败".format(name, e))
else:
self.log.info("点击{},元素[{}]点击成功".format(name, *args))
二、页面层(调用基类进行页面元素定位,页面操作)
page1
######项目页面
from PageObjects.BaseSelenium import BaseSelenium
from selenium.webdriver.common.by import By
class Tt(BaseSelenium):
# def __init__(self,browser_type='chrome',url = 'www.baidu.com'):
# super(Tt, self).__init__(browser_type='chrome',url = 'www.baidu.com')
def test_baidu(self,key):
self.send_key(key, (By.ID, 'kw'))
self.element_presence_click('点击百度一下',(By.ID,'su'))
def clear(self):
self.clear_value((By.ID, 'kw'))
page2文章来源地址https://www.toymoban.com/news/detail-507651.html
######项目页面
from PageObjects.BaseSelenium import BaseSelenium
from selenium.webdriver.common.by import By
class Tt1(BaseSelenium):
# def __init__(self,browser_type='chrome',url = 'www.baidu.com'):
# super(Tt1, self).__init__(browser_type='chrome',url = 'www.baidu.com')
def test_baidu1(self):
self.send_key('222', (By.ID, 'kw'))
self.element_presence_click('点击百度一下',(By.ID,'su'))
def clear(self):
self.clear_value((By.ID, 'kw'))
三、用例层(调用页面层组合成用例)
from PageLocators.page import Tt
from PageLocators.page1 import Tt1
from PageObjects.BaseSelenium import driver
from selenium.webdriver.common.by import By
class Test_1():
def setup_class(self):
d=driver().open_browser('chrome')
self.baidu = Tt(d)
self.baidu1 = Tt1(d)
self.baidu.open_url(url='www.baidu.com')
def test1(self):
self.baidu.test_baidu('LZP')
time.sleep(2)
self.baidu.clear_value((By.ID, 'kw'))
def test2(self):
self.baidu1.test_baidu1()
time.sleep(2)
self.baidu1.clear()
def test3(self):
self.baidu.test_baidu('LP')
time.sleep(2)
self.baidu.clear()
def teardown_class(self):
self.baidu.quit()
if __name__=='__main__':
pytest.main(['-s','test.py','-W','ignore:Module already imported:pytest.PytestWarning'])
文章来源:https://www.toymoban.com/news/detail-507651.html
到了这里,关于python+selenium自动化测试关键字驱动的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!