How to use browser_name method in Playwright Python

Best Python code snippet using playwright-python

app_selenium.py

Source:app_selenium.py Github

copy

Full Screen

1from selenium.webdriver.chrome.options import Options as ChromeOptions2from selenium.webdriver.firefox.options import Options as FirefoxOptions3from selenium.webdriver.ie.options import Options as IeOptions4from selenium import webdriver5from selenium.webdriver.common.action_chains import ActionChains6from selenium.webdriver.support.select import Select7from selenium.webdriver.support.ui import WebDriverWait8from selenium.webdriver.support import expected_conditions as EC9from selenium.webdriver.common.by import By10import getpass11import time12import re13import traceback14driver = '' # 浏览器driver15driver_dict = {} # 浏览器driver字典类型,方便利用key定位,16driver_num = 0 # 动态key,17def driver_key_num(driver):18 """19 动态driver以全局字典形式输出,20 :param driver: driver,21 :return:字典的key,22 """23 global driver_num24 global driver_dict25 driver_num_key = "driver_key" + str(driver_num)26 now_num = driver_num27 driver_num += 128 driver_dict[driver_num_key] = driver29 driver_key = list(driver_dict.keys())30 return driver_key[now_num]31def frame_xpath(browser_name, xpath, frame_flag=False):32 """33 xpath切分,34 :param browser_name: 浏览器driver,35 :param xpath: 待处理xpath,36 :param frame_flag: 是否有切换frame,37 :return: xpath38 """39 try:40 xpath.index(",/")41 xpath_list = xpath.split(",")42 for i in range(len(xpath_list)-1):43 browser_name.switch_to.frame(browser_name.find_element_by_xpath(xpath_list[i]))44 frame_flag = True45 return xpath_list[-1], frame_flag46 except ValueError as ve:47 #print(ve)48 return xpath, frame_flag49def frame_handle(browser_name, frame_location, frame_type):50 """51 frame切换,52 :param browser_name: 浏览器driver,53 :param frame_location: frame定位值,54 :param frame_type: frame定位类型,55 :return:56 """57 if frame_location:58 if frame_type == "frame_str":59 browser_name.switch_to.frame(frame_location)60 else:61 browser_name.switch_to.frame(int(frame_location) - 1)62 return63def driver_handle(browser_name):64 """65 切换当前浏览器driver,66 :param browser_name: driver变量名,67 :return:driver,68 """69 if browser_name:70 return driver_dict[browser_name]71 else:72 global driver73 return driver74# 考虑下要不要合成一个函数,75def browser_chrome(browser_path="", driver_path=""):76 """77 谷歌内核浏览器兼容,78 :param browser_path: 浏览器路径,79 :param driver_path: 驱动路径,80 :return: driver,81 """82 global driver83 if len(browser_path) > 0:84 options = ChromeOptions()85 options.binary_location = browser_path86 else:87 options = None88 if len(driver_path) == 0 :89 driver_path = "chromedriver"90 driver = webdriver.Chrome(executable_path=driver_path, options=options)91 return driver92def browser_ie(browser_path="", driver_path=""):93 """94 ie内核浏览器兼容,95 :param browser_path: 浏览器路径,96 :param driver_path: 驱动路径,97 :return: driver,98 """99 global driver100 if len(browser_path) > 0:101 options = IeOptions()102 options.binary_location = browser_path103 else:104 options = None105 if len(driver_path) == 0 :106 driver_path = "IEDriverServer.exe"107 driver = webdriver.Ie(executable_path=driver_path, options=options) # 需要在设置-安全-四个区域中统一启用安全模式,108 return driver109def browser_firefox(browser_path="", driver_path=""):110 """111 火狐内核浏览器兼容,112 :param browser_path: 浏览器路径,113 :param driver_path: 驱动路径,114 :return: driver,115 """116 global driver117 if len(browser_path) > 0:118 options = FirefoxOptions()119 options.binary_location = browser_path120 else:121 options = None122 if len(driver_path) == 0 :123 driver_path = "geckodriver"124 driver = webdriver.Firefox(executable_path=driver_path, options=options)125 return driver126def open_selenium(url, browser_type="br360", path_selenium="", chrome_driver="", open_type="newDriver"):127 """128 打开浏览器,1129 :param url: 打开网站地址,130 :param path_selenium: 浏览器地址,131 :param chrome_driver: 驱动地址,132 :param open_type: 打开类型,133 :param browser_type: 浏览器类型,134 :return: driver,135 """136 browser_select = {137 "br360" : browser_chrome,138 "chrome" : browser_chrome,139 "firefox": browser_firefox,140 "ie": browser_ie141 }142 sys_name = getpass.getuser()143 if len(path_selenium) == 0 and browser_type == "br360":# 360默认地址,测试使用,144 path_selenium = r"C:\Users\%s\AppData\Roaming\360se6\Application\360se.exe" % sys_name # 360默认安装位置,145 if len(chrome_driver) == 0 and browser_type == "br360":146 chrome_driver = r'C:\Users\%s\Desktop\chromedriver.exe' % sys_name147 global driver148 if driver != '':149 if open_type == "newWindow" :150 """151 新标签,浏览器 新窗口打开连接,selenium没有,暂时使用js的,152 切换当前窗口,坑比较大,依赖网页,部分网页无法使用提示window.open not function,怀疑是依赖网页js,而部分网页js不全导致,153 """154 window_new = 'window.open("' + url + '");'155 driver.execute_script(window_new)156 windows = driver.window_handles157 driver.switch_to.window(windows[-1]) # 切换当前窗口,158 driver_key = driver_key_num(driver)159 return driver_key160 elif open_type == "nowWindow" :161 driver.get(url) # 当前标签,162 driver_key = driver_key_num(driver) # driver会有重复值,但是去掉的话,rpa无法输出,163 return driver_key164 else:165 driver = browser_select[browser_type](path_selenium, chrome_driver)166 # 设置请求超时时间,待优化,167 driver.set_page_load_timeout(600)168 driver.set_script_timeout(600)169 try:170 driver.get(url)171 except Exception as exc:172 print(exc)173 driver.execute_script("window.stop()")174 finally:175 driver_key = driver_key_num(driver)176 return driver_key177 else:178 driver = browser_select[browser_type](path_selenium, chrome_driver)179 # 设置请求超时时间,待优化,180 driver.set_page_load_timeout(600)181 driver.set_script_timeout(600)182 try:183 driver.get(url)184 except Exception as exc:185 print(exc)186 driver.execute_script("window.stop()")187 finally:188 driver_key = driver_key_num(driver)189 return driver_key190def click_selenium(xpath, click_type="left_click", browser_name=None):191 """192 点击事件,1193 :param xpath: xpath地址,194 :param click_type: 点击类型,195 :param browser_name: 对应浏览器driver,196 :return:197 """198 current_driver = driver_handle(browser_name)199 chain = ActionChains(current_driver)200 xpath, frame_flag = frame_xpath(current_driver, xpath)201 element = current_driver.find_element_by_xpath(xpath)202 click_dict = {203 "left_click" : chain.click,204 "left_double_click" : chain.double_click,205 "click_and_hold": chain.click_and_hold,206 "right_click": chain.context_click207 }208 click_dict[click_type](element).perform()209 windows = current_driver.window_handles210 current_driver.switch_to.window(windows[-1]) # 切换当前窗口,211 if frame_flag: # 退出frame,212 current_driver.switch_to.default_content()213 return214def grab_selenium(xpath, browser_name=None):215 """216 抓取单个信息,217 :param xpath: xpath地址,218 :param browser_name: 对应浏览器driver,219 :return: 单个抓取值,220 """221 current_driver = driver_handle(browser_name)222 xpath, frame_flag = frame_xpath(current_driver, xpath)223 data_info = current_driver.find_element_by_xpath(xpath).text224 if frame_flag: # 退出frame,225 current_driver.switch_to.default_content()226 return data_info227def batch_grab_selenium(xpath, browser_name=None):228 """229 抓取批量信息,230 :param xpath: xpath地址,231 :param browser_name: 对应浏览器driver,232 :return: 返回抓取的数组,233 """234 current_driver = driver_handle(browser_name)235 xpath, frame_flag = frame_xpath(current_driver, xpath)236 data_info_batch = current_driver.find_elements_by_xpath(xpath)237 data_infos = []238 for i in data_info_batch:239 data_infos.append(i.text)240 if frame_flag: # 退出frame,241 current_driver.switch_to.default_content()242 return data_infos243def close_selenium(close_type="allClose", browser_name=None):244 """245 关闭所有界面,退出driver,246 或者关闭除第一个以外的其他页面,1第一个页面句柄,247 :param browser_name: 对应浏览器driver,248 :return:249 """250 current_driver = driver_handle(browser_name)251 if close_type=="un_nowClose" :252 windows = current_driver.window_handles # 切换当前窗口,253 window_num = len(windows)254 for i in range(window_num-1): # 关闭第一个以外的页面,255 current_driver.switch_to.window(windows[i+1])256 current_driver.close()257 else:258 current_driver.quit()259 return260def close_selenium_page(browser_name=None):261 """262 关闭当前界面,1263 :param browser_name: 对应浏览器driver,264 :return:265 """266 current_driver = driver_handle(browser_name)267 current_driver.close()268 windows = current_driver.window_handles269 current_driver.switch_to.window(windows[-1]) # 切换当前窗口,270 return271def input_selenium(xpath, text, browser_name=None):272 """273 输入信息,1274 :param xpath: xpath地址,275 :param text: 输入内容,276 :param browser_name: 对应浏览器driver,277 :return:278 """279 current_driver = driver_handle(browser_name)280 xpath, frame_flag = frame_xpath(current_driver, xpath)281 current_driver.find_element_by_xpath(xpath).send_keys(text)282 if frame_flag: # 退出frame,283 current_driver.switch_to.default_content()284 return285def refresh_selenium(browser_name=None):286 """287 页面刷新,288 :param browser_name: 对应浏览器driver,289 :return:290 """291 current_driver = driver_handle(browser_name)292 current_driver.refresh()293 return294def back_selenium(browser_name=None):295 """296 页面后退,297 :param browser_name: 对应浏览器driver,298 :return:299 """300 current_driver = driver_handle(browser_name)301 current_driver.back()302 return303def forward_selenium(browser_name=None):304 """305 页面前进,306 :param browser_name: 对应浏览器driver,307 :return:308 """309 current_driver = driver_handle(browser_name)310 current_driver.forward()311 return312def max_selenium(browser_name=None):313 """314 当前窗口最大化,315 :param browser_name: 对应浏览器driver,316 :return:317 """318 current_driver = driver_handle(browser_name)319 current_driver.maximize_window()320 return321def url_selenium(browser_name=None):322 """323 获取当前driver对应的url,324 :param browser_name: 对应浏览器driver,325 :return: 返回当前url,326 """327 current_driver = driver_handle(browser_name)328 url = current_driver.current_url329 return url330def existence_selenium(xpath, browser_name=None):331 """332 判断元素是否存在,333 :param browser_name: 对应浏览器driver,334 :return: 是否存在,335 """336 current_driver = driver_handle(browser_name)337 xpath, frame_flag = frame_xpath(current_driver, xpath)338 flag = True339 try:340 current_driver.find_element_by_xpath(xpath)341 except Exception as exc:342 flag = False343 finally:344 if frame_flag: # 退出frame,345 current_driver.switch_to.default_content()346 return flag347def attribute_selenium(xpath, attribute_name="", browser_name=None):348 """349 获取元素属性,350 :param xpath: xpath路径,351 :param attribute_name: 属性名称,352 :param browser_name: 对应浏览器driver,353 :return: 属性值,354 """355 current_driver = driver_handle(browser_name)356 xpath, frame_flag = frame_xpath(current_driver, xpath)357 attribute = current_driver.find_elements_by_xpath(xpath)358 attribute_value = []359 if attribute_name=="" :360 attribute_name="outerHTML"361 # attribute_name = "innerHTML"362 for i in attribute:363 attribute_value.append(i.get_attribute(attribute_name))364 if frame_flag: # 退出frame,365 current_driver.switch_to.default_content()366 return attribute_value367def select_selenium(xpath, text, match_type="equal_match", browser_name=None):368 """369 选择下拉框,370 :param xpath: xpath路径,371 :param text: 下拉框匹配文本,372 :param match_type: 匹配类型,373 :param browser_name: 对应浏览器driver,374 :return:375 """376 current_driver = driver_handle(browser_name)377 # frame_handle(current_driver, frame_location, frame_type)378 xpath, frame_flag = frame_xpath(current_driver, xpath)379 selector = Select(current_driver.find_element_by_xpath(xpath))380 like_text = []381 if match_type == "like_match" :382 pattern = ".*" + text + ".*"383 for i in selector.options:384 temp_text = re.findall(pattern, i.text)385 if len(temp_text)>0 :386 like_text.extend(temp_text)387 if len(like_text)>0:388 selector.select_by_visible_text(like_text[0])389 if frame_flag: # 退出frame,390 current_driver.switch_to.default_content()391 return392 else:393 if frame_flag: # 退出frame,394 current_driver.switch_to.default_content()395 return396 selector.select_by_visible_text(text)397 if frame_flag: # 退出frame,398 current_driver.switch_to.default_content()399 return400def selenium_driver_wait(xpath, browser_name=None, wait_second=20):401 """402 显示等待,等待元素加载,403 :param xpath: xpath路径,404 :param wait_second: 默认超时时间,405 :param browser_name: 浏览器key,406 :return: 是否加载完成,407 """408 current_driver = driver_handle(browser_name)409 wait_flag = False410 try:411 WebDriverWait(current_driver, int(wait_second), 0.5).until(EC.presence_of_element_located((By.XPATH, xpath)))412 wait_flag = True413 return wait_flag414 except Exception as exc:415 print(exc)416 return wait_flag417def alert_grab_selenium(browser_name=None, time_out=20):418 current_driver = driver_handle(browser_name)419 try:420 WebDriverWait(current_driver, int(time_out), 0.5).until(EC.alert_is_present())421 alert = current_driver.switch_to.alert422 return alert.text423 except Exception as exc:424 #print(exc)425 return426 #current_driver.switch_to.active_element427def alert_click_selenium(browser_name=None, time_out=20, operation_type="confirm"):428 current_driver = driver_handle(browser_name)429 try:430 WebDriverWait(current_driver, int(time_out), 0.5).until(EC.alert_is_present())431 alert = current_driver.switch_to.alert432 if operation_type=="confirm" :433 alert.accept()434 else:435 alert.dismiss()436 return True437 except Exception as exc:438 err_info= traceback.format_exc()439 return err_info440def test_br():441 """442 浏览器测试,443 :return:444 """445 if not None:446 print(len(""))447 # options = firefox_options()448 # options.binary_location = r"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"449 # driver_firefox = webdriver.Firefox(options=None, executable_path="geckodriver")450 # driver_firefox.get('https://www.baidu.com')451 # ie_path = r'C:\Users\shen\Desktop\IEDriverServer.exe' #需要在设置-安全-四个区域中统一启用安全模式,452 # driver_ie = webdriver.Ie(executable_path=ie_path)453 # driver_ie.get('https://www.baidu.com')454 chrome_path = r'C:\Users\shen\Desktop\chromedriver_win32 (1)\chromedriver.exe'455 driver_chrome1 = webdriver.Chrome(executable_path=chrome_path)456 driver_chrome1.get('https://www.baidu.com')457 driver_chrome2 = webdriver.Chrome(executable_path=chrome_path)458 driver_chrome2.get('https://m.jb51.net/w3school/tiy/t.asp-f=html_select_name.htm')459 input_selenium('//*[@id="kw"]', 'python', driver_chrome1)460 # select_selenium('/html/body/select', 'Au', 'like_match', browser_name=driver_chrome1, frame_location="i")461 # print(attribute_selenium('/html/body/select', browser_name=driver_chrome1))462 time.sleep(5)463 driver_chrome1.quit()464 # print(driver_chrome2)465def test():466 """467 其他测试,468 :return:469 """470 # 需要的文件的路径471 path = r'./'472 # 打印绝对路径473 #return os.path.abspath(path)474 # 获取系统用户名,475 print(getpass.getuser())476 sys_name = getpass.getuser()477 # C:\Users\shen\AppData\Roaming\360se6\Application\360se.exe478 path_selenium = r"C:\Users\%s\AppData\Roaming\360se6\Application\360se.exe" % sys_name479 print(path_selenium)480 print()481 print(type(driver))482if __name__ == '__main__':483 #test(),资源加载不到的, iframe的,使用js的,484 """485 https://hao.360.com/?wd_xp1486 http://rpaii.com/#487 https://www.baidu.com/488 //*[@id="kw"]489 //*[@id="su"]490 //div[contains(@class, 'c-container')]/h3491 //*[@id="hotsearch-content-wrapper"]/li[1]/a/span[2]492 //li[contains(@class, 'hotsearch-item')]493 file:///C:/Users/shen/Desktop/1.html494 /html/body/select495 Audi496 """497 open_selenium("file:///C:/Users/shen/Desktop/alert.html")498 #time.sleep(1)499 #print(selenium_driver_wait('//*[@attr_name="attr_value"]', 60))500 #open_selenium("file:///C:/Users/shen/Desktop/1.html")501 #open_selenium("https://m.jb51.net/w3school/tiy/t.asp-f=html_select_name.htm")502 #open_selenium("https://www.w3school.com.cn/tiy/t.asp?f=html_select", browser_type="ie", chrome_driver=r'C:\Users\shen\Desktop\IEDriverServer.exe')503 #open_selenium("https://www.baidu.com")504 #input_selenium('//*[@id="kw"]', 'python')505 print(grab_selenium("/html/body/div"))506 click_selenium('/html/body/button[1]')507 time.sleep(1)508 print(alert_grab_selenium())509 #time.sleep(5)510 time.sleep(1)511 alert_click_selenium()512 time.sleep(1)513 print(grab_selenium("/html/body/div"))514 click_selenium('/html/body/button[2]')515 time.sleep(1)516 print(alert_grab_selenium())517 alert_click_selenium(operation_type="cancle")518 time.sleep(1)519 # alert_click_selenium()520 # time.sleep(1)521 print(grab_selenium("/html/body/div"))522 #aa = grab_selenium("//li[contains(@class, 'hotsearch-item')]")523 #print(grab_selenium("/html/body/div"))524 #print(batch_grab_selenium("//div[contains(@class, 'c-container')]/h3"))525 #print(attribute_selenium('/html/body/select'))526 #print(attribute_selenium('/html/body/select',"name"))527 #select_selenium('//*[@id="a1"],//*[@id="b2"],/html/body/select','Audi','like_match')528 #print(grab_selenium('//*[@id="a1"],//*[@id="b2"],/html/body/select'))529 #time.sleep(5)530 close_selenium("allClose")531 #test_br()532 #print(frame_xpath("/html/body/iframe[1],/html/body/iframe[2],/html/body/iframe,/html/body/select"))...

Full Screen

Full Screen

linux_browser_driver.py

Source:linux_browser_driver.py Github

copy

Full Screen

1# Copyright (C) 2016 Igalia S.L. All rights reserved.2#3# Redistribution and use in source and binary forms, with or without4# modification, are permitted provided that the following conditions are5# met:6#7# * Redistributions of source code must retain the above copyright8# notice, this list of conditions and the following disclaimer.9#10# * Redistributions in binary form must reproduce the above11# copyright notice, this list of conditions and the following disclaimer12# in the documentation and/or other materials provided with the13# distribution.14#15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.26import os27import sys28import tempfile29import logging30import subprocess31try:32 import psutil33except ImportError:34 pass35from webkitpy.benchmark_runner.utils import force_remove36from browser_driver import BrowserDriver37_log = logging.getLogger(__name__)38class LinuxBrowserDriver(BrowserDriver):39 browser_name = None40 process_search_list = []41 platform = 'linux'42 def __init__(self):43 self.process_name = self._get_first_executable_path_from_list(self.process_search_list)44 if self.process_name is None:45 raise ValueError('Cant find executable for browser {browser_name}. Searched list: {browser_process_list}'.format(46 browser_name=self.browser_name, browser_process_list=self.process_search_list))47 def prepare_env(self, config):48 self._browser_process = None49 self._browser_arguments = None50 self._temp_profiledir = tempfile.mkdtemp()51 self._test_environ = dict(os.environ)52 self._test_environ['HOME'] = self._temp_profiledir53 def restore_env(self):54 force_remove(self._temp_profiledir)55 def close_browsers(self):56 if self._browser_process:57 if self._browser_process.poll() is None: # still running58 if 'psutil' in sys.modules:59 main_browser_process = psutil.Process(self._browser_process.pid)60 browser_children = main_browser_process.children(recursive=True)61 _log.info('Killing browser {browser_name} with pid {browser_pid} and cmd: {browser_cmd}'.format(62 browser_name=self.browser_name, browser_pid=self._browser_process.pid,63 browser_cmd=' '.join(main_browser_process.cmdline()).strip() or main_browser_process.name()))64 main_browser_process.kill()65 for browser_child in browser_children:66 if browser_child.is_running():67 _log.info('Killing still alive {browser_name} child with pid {browser_pid} and cmd: {browser_cmd}'.format(68 browser_name=self.browser_name, browser_pid=browser_child.pid,69 browser_cmd=' '.join(browser_child.cmdline()).strip() or browser_child.name()))70 browser_child.kill()71 else:72 _log.info('Killing browser {browser_name} with pid {browser_pid}'.format(73 browser_name=self.browser_name, browser_pid=self._browser_process.pid))74 self._browser_process.kill()75 _log.warning('python psutil not found, cant check for '76 'still-alive browser childs to kill.')77 else:78 _log.error('Browser {browser_name} with pid {browser_pid} ended prematurely with return code {browser_retcode}.'.format(79 browser_name=self.browser_name, browser_pid=self._browser_process.pid,80 browser_retcode=self._browser_process.returncode))81 def launch_url(self, url, options, browser_build_path):82 if not self._browser_arguments:83 self._browser_arguments = [url]84 exec_args = [self.process_name] + self._browser_arguments85 _log.info('Executing: {browser_cmdline}'.format(browser_cmdline=' '.join(exec_args)))86 self._browser_process = subprocess.Popen(exec_args, env=self._test_environ,87 stdout=subprocess.PIPE,88 stderr=subprocess.STDOUT)89 def launch_webdriver(self, url, driver):90 try:91 driver.maximize_window()92 except Exception as error:93 _log.error('Failed to maximize {browser} window - Error: {error}'.format(browser=driver.name, error=error))94 _log.info('Launching "%s" with url "%s"' % (driver.name, url))95 driver.get(url)96 def _get_first_executable_path_from_list(self, searchlist):97 searchpath = [os.path.curdir] + os.environ['PATH'].split(os.pathsep)98 for program in searchlist:99 for path in searchpath:100 fullpath = os.path.abspath(os.path.join(path, program))101 if os.path.isfile(fullpath) and os.access(fullpath, os.X_OK):102 return fullpath103 return None104 def _screen_size(self):105 # load_subclasses() from __init__.py will load this file to106 # check the platform defined. Do here a lazy import instead of107 # trying to import the Gtk module on the global scope of this108 # file to avoid ImportError errors on other platforms.109 # Python imports are cached and only run once, so this should be ok.110 import gi111 gi.require_version('Gtk', '3.0')112 gi.require_version('Gdk', '3.0')113 from gi.repository import Gtk, Gdk114 if Gtk.get_major_version() == 3 and Gtk.get_minor_version() < 22:115 screen = Gtk.Window().get_screen()116 return screen.get_monitor_geometry(screen.get_primary_monitor())117 else:118 display = Gdk.Display.get_default()119 monitor = display.get_primary_monitor()...

Full Screen

Full Screen

test_subheader_nav.py

Source:test_subheader_nav.py Github

copy

Full Screen

1import unittest2import sys3import os4sys.path.append(os.path.join(os.path.dirname(__file__), '..'))5from core import test_core6from utils import env_util, webdriver_util7WEB_SITE = env_util.get_env_url()8START = WEB_SITE+'start-your-business'9START_BEST = WEB_SITE+'7638-best-background-check-services.html'10START_ARTICLE = WEB_SITE+'7623-businesses-for-sale.html'11GROW = WEB_SITE+'grow-your-business'12BUILD = WEB_SITE+'build-your-career'13LEAD = WEB_SITE+'lead-your-team'14FIND = WEB_SITE+'find-a-solution'15ARTICLE = WEB_SITE+'7400-putting-apple-pay-to-work-and-how-you-can-too.html'16 17def verifySubNavigation(self, expected_color, browser_name):18 sub_nav_bar = self.driver.find_element_by_css_selector('.altNav.unit')19# nav_link_bar_part = self.driver.find_element_by_css_selector('.altNavList.line.bg'+str(nav_number))20 self.assertTrue(sub_nav_bar.is_displayed(), 'sub navigation bar is not displayed')21 nav_links = self.driver.find_elements_by_css_selector('.altNavList.line.mqMedOff .subItem>a')22 for link in nav_links:23 self.assertTrue(link.is_displayed(), 'sub nav link is not displayed')24 sub_nav = self.driver.find_element_by_css_selector('.wrap.altNavLiner')25# nav_link_color = nav_link_bar_part.value_of_css_property('background-color')26 sub_nav_color = sub_nav.value_of_css_property('background-color')27 sub_nav_bar_color = sub_nav_bar.value_of_css_property('background-color')28 self.assertEquals(sub_nav_color,sub_nav_bar_color, 'nav bar color and color behind nav links do not match')29 self.assertEqual(sub_nav_color, expected_color, 'color is not correct')30 side_ads_css = '#ctMedia'31 if(webdriver_util.is_element_present(self.driver, side_ads_css)):32 if("chrome" or "headless" in browser_name):33 expected_color = u'rgba(0, 0, 0, 0)'34 else:35 expected_color = u'rgb(0, 0, 0)'36 self.assertEquals(sub_nav_bar_color, expected_color, ' Nav bar is covering background/side ads')37class SubheaderTestCase(test_core.TestCore):38 def testStartBusinessPage(self):39 self.driver.get(START)40 browser_name = env_util.get_browser()41 if("chrome" or "headless" in browser_name):42 verifySubNavigation(self, u'rgba(0, 83, 186, 1)', browser_name)43 else:44 verifySubNavigation(self, u'rgb(0, 83, 186)', browser_name)45 46 def testStartBusinessBestPick(self):47 self.driver.get(START_BEST)48 browser_name = env_util.get_browser()49 if("chrome" or "headless" in browser_name):50 verifySubNavigation(self, u'rgba(23, 166, 255, 1)', browser_name)51 else:52 verifySubNavigation(self, u'rgb(23, 166, 255)', browser_name)53 54 def testStartBusinessArticle(self):55 self.driver.get(START_ARTICLE)56 browser_name = env_util.get_browser()57 if("chrome" or "headless" in browser_name):58 verifySubNavigation(self, u'rgba(0, 83, 186, 1)', browser_name)59 else:60 verifySubNavigation(self, u'rgb(0, 83, 186)', browser_name)61 62 def testGrowBusiness(self):63 self.driver.get(GROW)64 browser_name = env_util.get_browser()65 if("chrome" or "headless" in browser_name):66 verifySubNavigation(self, u'rgba(205, 0, 93, 1)', browser_name)67 else:68 verifySubNavigation(self, u'rgb(205, 0, 93)', browser_name) 69 70 def testBuildCareer(self):71 self.driver.get(BUILD)72 browser_name = env_util.get_browser()73 if("chrome" or "headless" in browser_name):74 verifySubNavigation(self, u'rgba(0, 205, 183, 1)', browser_name)75 else:76 verifySubNavigation(self, u'rgb(0, 205, 183)', browser_name)77 78 def testLeadTeam(self):79 self.driver.get(LEAD)80 browser_name = env_util.get_browser()81 if("chrome" or "headless" in browser_name):82 verifySubNavigation(self, u'rgba(255, 93, 21, 1)', browser_name)83 else:84 verifySubNavigation(self, u'rgb(255, 93, 21)', browser_name)85 86 def testFindSolution(self):87 self.driver.get(FIND)88 browser_name = env_util.get_browser()89 if("chrome" or "headless" in browser_name):90 verifySubNavigation(self, u'rgba(23, 166, 255, 1)', browser_name)91 else:92 verifySubNavigation(self, u'rgb(23, 166, 255)', browser_name)93 94 def testArticle(self):95 self.driver.get(ARTICLE)96 browser_name = env_util.get_browser()97 if("chrome" or "headless" in browser_name):98 verifySubNavigation(self, u'rgba(205, 0, 93, 1)', browser_name)99 else:100 verifySubNavigation(self, u'rgb(205, 0, 93)', browser_name)101 102if __name__ == "__main__":103 suite = unittest.TestLoader().loadTestsFromTestCase(SubheaderTestCase)...

Full Screen

Full Screen

statistics_handler.py

Source:statistics_handler.py Github

copy

Full Screen

1#!/usr/bin/python2.42#3# Copyright 2010 Google Inc. All Rights Reserved.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16"""Computes average scores for browsers."""17import datetime18from google.appengine.ext import db19from google.appengine.ext import webapp20from google.appengine.ext.webapp.util import run_wsgi_app21from handlers import base22from models import browser_score23COMPUTE_AVERAGE_SCORE_URL = '/stats/average'24COMPUTE_MULTI_SUITE_AVERAGE_URL = '/stats/multi'25class ComputeAverageScore(webapp.RequestHandler):26 """Handler for computing average suite scores.27 Computes average scores for each browser involved in a suite.28 """29 # Disable 'Invalid method name' lint error.30 # pylint: disable-msg=C640931 def get(self):32 """Calculates the average suite score per test browser."""33 suite_key = self.request.get('suite')34 suite = db.get(db.Key(suite_key))35 test_browsers = suite.GetTestBrowsers()36 # Fetch all the results (page-delta).37 pd_results = []38 query = suite.results39 pd = query.fetch(1000)40 last_cursor = query.cursor()41 while pd:42 pd_results.extend(pd)43 query = query.with_cursor(last_cursor)44 pd = query.fetch(1000)45 last_cursor = query.cursor()46 scores = {}47 counts = {}48 for test_browser in test_browsers:49 scores[test_browser.key().name()] = 050 counts[test_browser.key().name()] = 051 for result in pd_results:52 # Check for invalid results53 if result.score < 0:54 continue55 browser_key = result.GetTestBrowser().key().name()56 # Only count results that are non-ignored.57 if not result.ignore:58 scores[browser_key] += result.score59 counts[browser_key] += 160 for test_browser in test_browsers:61 test_browser_key = test_browser.key().name()62 scores[test_browser_key] /= float(counts[test_browser_key])63 average_score = browser_score.GetOrInsertBrowserScore(suite, test_browser)64 average_score.layout_score = scores[test_browser_key]65 average_score.num_urls = counts[test_browser_key]66 average_score.date = datetime.datetime.utcnow()67 average_score.put()68 self.redirect('/suite/stats?suite=%s' % suite_key)69class GetAverageScoreOfMultiSuites(base.BaseHandler):70 """Handler for computing average score among multiple suites.71 Computes the average scores for each browser in the specified suites.72 """73 # Disable 'Invalid method name' lint error.74 # pylint: disable-msg=C640975 def get(self):76 """Calculates the average score per test browser across mutliple suites."""77 suite_keys = self.request.get_all('suite')78 browser_scores = {}79 browser_num_urls = {}80 for suite_key in suite_keys:81 suite = db.get(db.Key(suite_key))82 for test_browser in suite.GetTestBrowsers():83 score = browser_score.GetOrInsertBrowserScore(suite, test_browser)84 browser_name = unicode(test_browser)85 if not browser_name in browser_scores:86 browser_scores[browser_name] = 087 browser_num_urls[browser_name] = 088 total_urls = browser_num_urls[browser_name] + score.num_urls89 browser_scores[browser_name] = (90 browser_scores[browser_name] * browser_num_urls[browser_name] +91 score.layout_score * score.num_urls) / float(total_urls)92 browser_num_urls[browser_name] = total_urls93 score_output = []94 num_urls_output = []95 keys = browser_scores.keys()96 keys.sort()97 for browser_name in keys:98 score_output.append('["%s", %f]' % (browser_name,99 browser_scores[browser_name]))100 num_urls_output.append('%s (%d urls)' % (browser_name,101 browser_num_urls[browser_name]))102 template_values = {'browser_scores': ',\n'.join(score_output),103 'test_browsers': num_urls_output}104 self.RenderTemplate('suite_stats.html', template_values)105application = webapp.WSGIApplication(106 [(COMPUTE_AVERAGE_SCORE_URL, ComputeAverageScore),107 (COMPUTE_MULTI_SUITE_AVERAGE_URL, GetAverageScoreOfMultiSuites)],108 debug=True)109def main():110 run_wsgi_app(application)111if __name__ == '__main__':...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful