webUI自动化(二)关键字封装、chrome_options、断言
一、关键字的解析
- 什么是关键字?实际就是封装。
给出“做什么”和“原材料”,就等于一个想要的步骤。
“做什么” ==》函数名
“原材料” ==》参数
- 封装形式
函数 or 类
二、实例
- 封装前代码
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.bilibili.com/")
time.sleep(2)
driver.find_element_by_xpath("//input[@class='nav-search-input']").send_keys("python")
time.sleep(1)
driver.find_element_by_xpath("//div[@class='nav-search-btn']").click()
time.sleep(2)
driver.quit()
- 创建base文件夹,创建base_tools.py,进行关键字封装
from time import sleep
from selenium import webdriver
from base.chrome_options import chrome_options
class Base:
def __init__(self):
self.driver = webdriver.Chrome(chrome_options=chrome_options())
def open(self,url):
"""打开网址"""
self.driver.get(url)
def locate(self,ele_type,ele_value):
"""定位"""
try:
ele = self.driver.find_element(ele_type,ele_value)
return ele
except:
print("定位失败")
raise
def input(self,ele_type,ele_value,txt):
"""输入"""
self.locate(ele_type,ele_value).send_keys(txt)
def click(self,ele_type,ele_value):
"""单击"""
self.locate(ele_type, ele_value).click()
def max_window(self):
"""窗口最大化"""
self.driver.maximize_window()
def switch_to_iframe(self,iframe_value):
"""切换到iframe"""
self.driver.switch_to.frame(iframe_value)
def switch_to_windows(self):
"""切换新窗口"""
windows = self.driver.window_handles
self.driver.switch_to.window(windows[-1])
def assert_locate(self,ele_type,ele_value):
"""断言"""
assert self.locate(ele_type,ele_value) is not None,'断言失败'
print('断言成功!')
@staticmethod
def wait(second_num):
"""固定等待"""
sleep(second_num)
def quit(self):
"""退出浏览器"""
self.driver.quit()
- 优化后的代码
from base.base_tools import Base
b = Base()
b.open("https://www.bilibili.com/")
b.wait(2)
b.input("xpath","//input[@class='nav-search-input']","python")
b.wait(1)
b.click("xpath","//div[@class='nav-search-btn']")
b.wait(2)
b.switch_to_windows()
b.assert_locate("xpath","//button[text()='综合排序']")
b.wait(2)
b.quit()
三、chrome_options
- base文件夹下,新建chrome_options.py,chrome的工具。
- 配置浏览器在启动之初,应该要附加的设置内容。ChromeOptions专门用于配置对应的chrome浏览器。
from selenium import webdriver
def chrome_options():
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches',['enable-automation'])
options.add_argument('start-maximized')
prefs = {"credentials_enable_service": False, "pofile.password_manager_enable": False}
options.add_experimental_option("prefs", prefs)
options.add_argument("--no-sandbox")
options.add_argument('--kiosk-printing')
return options