Best Python code snippet using selene_python
app_selenium.py
Source:app_selenium.py
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"))...
linux_browser_driver.py
Source:linux_browser_driver.py
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()...
test_subheader_nav.py
Source:test_subheader_nav.py
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)...
statistics_handler.py
Source:statistics_handler.py
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__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!