def web_driver(request): """返回driver,现在是Chrome""" global driver HEADLESS = get_web_config().get("HEADLESS") DEBUGGER = get_web_config().get("DEBUGGER") if HEADLESS is True: __options = Options() __options.add_argument('--headless') driver = WebChrome(chrome_options=__options) elif DEBUGGER is True: # 如果需要使用已经打开的,chrome浏览器的debugger模式,需要把以下三行代码释放 chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") driver = WebChrome(options=chrome_options) else: __options = Options() # 设置全屏 __options.add_argument('--start-maximized') # 设置开发者模式 __options.add_experimental_option( "excludeSwitches", ["ignore-certificate-errors", "enable-automation"]) driver = WebChrome(chrome_options=__options) yield driver driver.close() def end(): driver.quit() request.addfinalizer(end)
def job1(useid, password): #通过python自带的模块判断是不是节假日 nowTime = datetime.date(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day) print(is_workday(nowTime)) if is_workday(nowTime): print('Its weekday') driver = WebChrome() driver.implicitly_wait(20) driver.get( "http://sso.portal.unicom.local/eip_sso/aiportalLogin.html?appid=na186&success=http://service.aiportal.unicom.local/ssoclient/ssologin&error=http://sso.portal.unicom.local/eip_sso/aiportalLogin.html&return=http://sso.portal.unicom.local/eip_sso/aiportalLogin.html" ) driver.find_element_by_id('login').send_keys(useid) driver.find_element_by_id('password').send_keys(password) driver.find_element_by_xpath("//button[@class='login_botton']").click() driver.find_element_by_xpath( "//div[@class='pan' and @label='人力资源2.0']").click() driver.switch_to_new_tab() driver.find_element_by_xpath( "//a[@class = 'gn_block gn_block1']").click() driver.switch_to_new_tab() driver.find_element_by_xpath( "//button[@class='ant-btn sign-btn signout ant-btn-primary']" ).click() driver.quit() else: print('Its holiday')
def __init__(self, target_url): self.driver = WebChrome() self.driver.get(target_url) self.driver.implicitly_wait(20) self.exp_user_dic = [ "admin' or 'a'='a", "'or'='or'", "admin' or '1'='1' or 1=1", "')or('a'='a", "'or 1=1 -- -" ] self.exp_pass_dic = self.exp_user_dic self.static_user_dic = [ 'admin', 'system', 'sa', 'test', 'manager', 'root', 'user', 'www', 'web', 'username', 'guest', 'name', 'zhanghao', 'yonghu', 'email', 'account' ] self.suffix_dic = ['', '123', '888', '666', '123456'] self.static_pass_dic = [ '{user}', '123456', '{user}888', '12345678', '123123', '88888888', '888888', 'password', '123456a', '{user}123', '{user}123456', '{user}666', '{user}2018', '123456789', '654321', '666666', '66666666', '1234567890', '8888888', '987654321', '0123456789', '12345', '1234567', '000000', '111111', '5201314', '123123', 'pass', 'password', 'P@ssw0rd', 'P@ssw0rd2019', 'P@ssw0rd2020', 'P@ssw0rd2021' ] self.password_inputbox_id = '' self.username_inputbox_id = ''
def setup(self): super(TestWebBaseCase, self).setup() self.driver = WebChrome() self.driver.implicitly_wait(5) self.driver.get(BASEURL) # 使用cookie打开浏览器 with shelve.open(f"{mydbs_dir}/cookies") as db: # coo = self.driver.get_cookies() # db["cookies"] = coo cookies = db["cookies"] for cookie in cookies: if "expiry" in cookie.keys(): cookie.pop("expiry") continue self.driver.add_cookie(cookie) self.driver.get(BASEURL) self.log.info("进入主界面") self.main_page = MainPage(self.driver)
import unittest from selenium import webdriver from airtest_selenium.proxy import WebChrome from time import sleep options = webdriver.chrome.options.Options() options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") driver = WebChrome(chrome_options=options) driver.implicitly_wait(20) driver.get("http://td2.qingbaomofang.com/dashboard/market") sleep(1) # 关注列表 driver.find_element_by_xpath( "/html/body/div[2]/div/div/div/div/div/ul/div/li[4]/div").click() sleep(1) driver.find_element_by_xpath( "/html/body/div[2]/div/div/div/div/div/ul/div/li[4]/ul/li/ul/li/span" ).click() sleep(5) class Assert_test(unittest.TestCase): # 打开店铺详情 driver.find_element_by_xpath("//a[@title='perfectdiary旗舰店']").click() # 按月 driver.find_element_by_xpath( "/html/body/div[2]/div[2]/div[2]/div/div[3]/div[2]/div/div[1]/div/div[1]/div[1]/div[3]/div[1]/span" ).click() sleep(1) driver.find_element_by_xpath("/html/body/ul/li[2]").click()
else: pass if poco('一键购买').exists(): poco('一键购买').click() sleep(20) if exists(Template(r"tpl1572316650111.png", record_pos=(-0.344, -0.186), resolution=(2560, 1440))): log('购买成功') pass stop_app(app_id) sleep(3) clear_app(app_id) ################################################################ from airtest.core.api import * from airtest_selenium.proxy import WebChrome game_id = '600144' driver = WebChrome() driver.implicitly_wait(20) sleep(3) driver.maximize_window() driver.get("http://tech-support.upltv.com:82/index") driver.find_element_by_xpath("//a[@href='/auth/login']").click() driver.find_element_by_xpath("//input[@autocomplete='on']").send_keys('*****@*****.**') driver.find_element_by_xpath("//input[@autocomplete='off']").send_keys('Temp2019') driver.find_element_by_xpath("//input[@value='登录']").click() sleep(5) Logging('准备数据上报------------------------------------------') driver.find_element_by_xpath("//*[@id=\"bs-example-navbar-collapse-1\"]/ul/li/a/span").click() driver.find_element_by_xpath("//a[@href='/report/analysis']").click()
def open_browser( self, url: Optional[str] = None, browser: str = "Chrome", alias: Optional[str] = None, remote_url: Union[bool, str] = False, headless: Optional[bool] = False, options: Any = None, device: Optional[str] = None, executable_path: Optional[str] = None, service_args: Union[dict, None, str] = None, desired_capabilities: Union[dict, None, str] = None) -> str: """ 启动浏览器类型可选: Firefox, Chrome, Ie, Opera, Safari, PhantomJS, 可模拟移动设备 """ if browser not in [ 'Firefox', 'Chrome', 'Ie', 'Opera', 'Safari', 'PhantomJS' ]: raise Exception( '浏览器类型不对, 仅可选: Firefox, Chrome, Ie, Opera, Safari, PhantomJS') remote_url = remote_url or self.remote_url browser = browser or self.browser headless = headless or self.headless alias = alias or self.alias device = device or self.device executable_path = executable_path or self.executable_path options or self.options service_args = service_args or self.service_args desired_capabilities = desired_capabilities or self.desired_capabilities if remote_url: if browser == 'Chrome': chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-setuid-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') if headless: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') if device: mobile_emulation = {'deviceName': device} chrome_options.add_experimental_option( 'mobileEmulation', mobile_emulation) browser_options = chrome_options elif browser == 'Firefox': firefox_options = webdriver.FirefoxOptions() firefox_options.add_argument('--disable-dev-shm-usage') if headless: firefox_options.add_argument('--headless') firefox_options.add_argument('--disable-gpu') browser_options = firefox_options else: browser_options = options desired_capabilities = desired_capabilities or {} desired_capabilities['browserName'] = browser.lower() driver = WebRemote(command_executor=remote_url, desired_capabilities=desired_capabilities, options=options or browser_options) # ctx.create_webdriver(driver_name='Remote', alias=alias, command_executor=remote_url, options=options, desired_capabilities=desired_capabilities) elif browser == 'Chrome': chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-setuid-sandbox') if headless: chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') if device: mobile_emulation = {'deviceName': device} chrome_options.add_experimental_option('mobileEmulation', mobile_emulation) if executable_path: driver = WebChrome(executable_path=executable_path, options=options or chrome_options, service_args=service_args, desired_capabilities=desired_capabilities) # ctx.create_webdriver(driver_name=browser, alias=alias, executable_path=executable_path, options=options or chrome_options, service_args=service_args, desired_capabilities=desired_capabilities) else: driver = WebChrome(options=options or chrome_options, service_args=service_args, desired_capabilities=desired_capabilities) # ctx.create_webdriver(driver_name=browser, alias=alias, options=options or chrome_options, service_args=service_args, desired_capabilities=desired_capabilities) elif browser == 'Firefox': firefox_options = webdriver.FirefoxOptions() if headless: firefox_options.add_argument('--headless') firefox_options.add_argument('--disable-gpu') if executable_path: driver = WebFirefox(executable_path=executable_path, options=options or firefox_options, service_args=service_args, desired_capabilities=desired_capabilities) # ctx.create_webdriver(driver_name=browser, alias=alias, executable_path=executable_path, options=options or firefox_options, service_args=service_args, desired_capabilities=desired_capabilities) else: driver = WebFirefox(options=options or firefox_options, service_args=service_args, desired_capabilities=desired_capabilities) # ctx.create_webdriver(driver_name=browser, alias=alias, options=options or firefox_options, service_args=service_args, desired_capabilities=desired_capabilities) else: if executable_path: self.create_webdriver( driver_name=browser, alias=alias, executable_path=executable_path, service_args=service_args, desired_capabilities=desired_capabilities) else: self.create_webdriver( driver_name=browser, alias=alias, service_args=service_args, desired_capabilities=desired_capabilities) driver = self.driver index = self.ctx.register_driver(driver=driver, alias=alias) if url: self.go_to(url) return index
options = Options() options.add_argument('--dns-prefetch-disable') options.add_argument("--disable-features=VizDisplayCompositor") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) options.add_argument('start-maximized') options.add_argument('enable-automation') options.add_argument('--no-sandbox') options.add_argument('--disable-infobars') options.add_argument('--disable-dev-shm-usage') options.add_argument('--disable-browser-side-navigation') options.add_argument('--disable-gpu') options.add_argument('--disable-extensions') driver = WebChrome(executable_path=chrome, options=options) driver.implicitly_wait(40) dfx = driver.find_element_by_xpath ser = CaseService() def main_setup(): try: driver.get(test_url) driver.maximize_window() dfx("//button[@type='submit']").click() except Exception as e: ser.find_JSerror(driver) print( '================================================================') print(e.args)
class Mytest(unittest.TestCase): """ 基类:整个用例执行前的操作以及公共的方法 """ dr = WebChrome(globalparam.executable_path) logger = Log() @classmethod def setUpClass(cls): """ 整个用例执行的前置条件 """ cls.logger.info('############################### START ###############################') cls.dr.maximize_window() def setUp(self): pass def tearDown(self): """ 每个用例执行的后置条件 """ # 用例执行报错立即截图 errors = self._outcome.errors for test, exc_info in errors: if exc_info: self.save_img('test') pass else: pass @classmethod def tearDownClass(cls): """ 整个用例执行的后置条件 """ cls.dr.quit() cls.logger.info('############################### End ###############################') @classmethod def save_img(self, img_name): """ 保存图片 保存的图片同时可用于展示在报告里 :param img_name: 要保存的图片的名称 """ img_path = abs_dir + '\{}-{}.png'.format(img_name, time.strftime('%Y-%m-%d_%H_%M_%S')) img_path = img_path.replace('\\', '/') # 将反斜杠\替换成/ print(img_path) # cls.dr.snapshot(filename=img_path) self.take_screenshot(self, file_path=img_path) img_path = img_path[img_path.index("/web_UItest"):] # 截取图片路径后面部分,用来拼接成相对路径 img_path ='http://localhost:63342'+ '{}'.format(img_path) print("<img src='" + img_path + "' width=600 />") # 把图片发送到 BR 报告里,BR 的特性 def take_screenshot(self, file_path): """ Get the current window screenshot. Usage: dr.take_screenshot('c:/test.png') """ t1 = time.time() try: self.dr.get_screenshot_as_file(file_path) self.my_print(msg="{0} Get the current window screenshot,path: {1}, Spend {2} seconds".format(success, file_path, time.time() - t1)) except Exception: self.my_print(msg="{0} Unable to get the current window screenshot,path: {1}, Spend {2} seconds".format( fail, file_path, time.time() - t1)) raise def my_print(msg): logger.info(msg)
def __init__(self): self.dr = WebChrome(globalparam.executable_path)
# -*- encoding=utf8 -*- __author__ = "Administrator" from airtest.core.api import * import sys # pip3 install pynput # pip3 install airtest-selenium # 得到绝对路径 abs_path = os.path.abspath(os.path.dirname(__file__)) # 得到公共用例目录 common_path = os.path.join(abs_path.split("airtest_auto")[0], "airtest_auto", "util") sys.path.append(common_path) from airtest_selenium.proxy import WebChrome driver = WebChrome(os.path.join(common_path, "chromedriver.exe")) driver.implicitly_wait(20) auto_setup(__file__) try: driver.get("http://www.baidu.com") except Exception as e: snapshot(msg="报错后截图") raise e finally: driver.close()
# -*- encoding=utf8 -*- __author__ = "Administrator" from airtest.core.api import * from selenium import webdriver from selenium.webdriver.common.keys import Keys from airtest_selenium.proxy import WebChrome from selenium.webdriver.common.action_chains import ActionChains#导入鼠标悬停模块 driver = WebChrome()#打开浏览器 # driver.implicitly_wait(10) auto_setup(__file__) driver.get("http://createwit.com/")#进入创智美业官网 time.sleep(2) driver.maximize_window()#浏览器窗口最大化 tag_element = driver.find_element_by_xpath("//a[@href='product.html']")#定位该元素 ActionChains(driver).move_to_element(tag_element).perform()#鼠标悬停到该元素 driver.find_element_by_link_text("ERP").click()#点击该元素 driver.assert_template(Template(r"tpl1583921002974.png", record_pos=(5.87, 1.895), resolution=(100, 100)), "是否定位至erp") driver.find_element_by_xpath("//img[@src='images/product/js_1.png']").click() driver.assert_template(Template(r"tpl1583921034507.png", record_pos=(7.63, 2.285), resolution=(100, 100)), "是否定位至讲师") js="window.scrollTo(0,document.body.scrollHeight)" driver.execute_script(js)#页面滑动至最底部 time.sleep(1) driver.assert_template(Template(r"tpl1583919799081.png", record_pos=(4.455, 7.99), resolution=(100, 100)), "验证是否滑动至最底部") driver.find_element_by_xpath("//a[@href='about.html']").click() driver.assert_template(Template(r"tpl1583918269179.png", record_pos=(3.38, 4.15), resolution=(100, 100)), "是否跳转至关于我们页面") driver.find_element_by_xpath("//a[@href='download.html']").click() driver.assert_template(Template(r"tpl1583918305017.png", record_pos=(3.245, 5.25), resolution=(100, 100)), "是否跳转至下载专区页面")