Best Python code snippet using playwright-python
dual_browser_story.py
Source:dual_browser_story.py
...206 @property207 def url(self):208 return self._url209 @property210 def browser_type(self):211 return self._browser_type212 def Run(self, shared_state):213 shared_state.current_tab.Navigate(self._url)214 shared_state.current_tab.WaitForDocumentReadyStateToBeComplete()215 shared_state.TakeMemoryMeasurement()216class DualBrowserStorySet(story_module.StorySet):217 """A story set that switches back and forth between two browsers."""218 def __init__(self, long_running=False):219 super(DualBrowserStorySet, self).__init__(220 archive_data_file='data/dual_browser_story.json',221 cloud_storage_bucket=story_module.PARTNER_BUCKET)222 self.long_running = long_running223 for query, url in zip(SEARCH_QUERIES, URL_LIST):224 # Stories that run on the android-webview browser....
bisect_variations.py
Source:bisect_variations.py
1# Copyright 2019 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4"""A script to bisect field trials to pin point a culprit for certain behavior.5Chrome runs with many experiments and variations (field trials) that are6randomly selected based on a configuration from a server. They lead to7different code paths and different Chrome behaviors. When a bug is caused by8one of the experiments or variations, it is useful to be able to bisect into9the set and pin-point which one is responsible.10Go to chrome://version/?show-variations-cmd. At the bottom, a few commandline11switches define the current experiments and variations Chrome runs with.12Sample use:13python bisect_variations.py --input-file="variations_cmd.txt"14 --output-dir=".\out" --browser=canary --url="https://www.youtube.com/"15"variations_cmd.txt" is the command line switches data saved from16chrome://version/?show-variations-cmd.17Run with --help to get a complete list of options this script runs with.18"""19import logging20import optparse21import os22import shutil23import subprocess24import sys25import tempfile26import split_variations_cmd27_CHROME_PATH_WIN = {28 # The following three paths are relative to %ProgramFiles(x86)%29 "stable": r"Google\Chrome\Application\chrome.exe",30 "beta": r"Google\Chrome\Application\chrome.exe",31 "dev": r"Google\Chrome Dev\Application\chrome.exe",32 # The following two paths are relative to %LOCALAPPDATA%33 "canary": r"Google\Chrome SxS\Application\chrome.exe",34 "chromium": r"Chromium\Application\chrome.exe",35}36_CHROME_PATH_MAC = {37 "stable": r"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",38 "beta": r"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",39 "dev": r"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",40 "canary": (r"/Applications/Google Chrome Canary.app/Contents/MacOS/"41 r"Google Chrome Canary"),42}43def _GetSupportedBrowserTypes():44 """Returns the supported browser types on this platform."""45 if sys.platform.startswith('win'):46 return _CHROME_PATH_WIN.keys()47 if sys.platform == 'darwin':48 return _CHROME_PATH_MAC.keys();49 raise NotImplementedError('Unsupported platform')50def _LocateBrowser_Win(browser_type):51 """Locates browser executable path based on input browser type.52 Args:53 browser_type: 'stable', 'beta', 'dev', 'canary', or 'chromium'.54 Returns:55 Browser executable path.56 """57 if browser_type in ['stable', 'beta', 'dev']:58 return os.path.join(os.getenv('ProgramFiles(x86)'),59 _CHROME_PATH_WIN[browser_type])60 else:61 assert browser_type in ['canary', 'chromium']62 return os.path.join(os.getenv('LOCALAPPDATA'),63 _CHROME_PATH_WIN[browser_type])64def _LocateBrowser_Mac(browser_type):65 """Locates browser executable path based on input browser type.66 Args:67 browser_type: A supported browser type on Mac.68 Returns:69 Browser executable path.70 """71 return _CHROME_PATH_MAC[browser_type]72def _LocateBrowser(browser_type):73 """Locates browser executable path based on input browser type.74 Args:75 browser_type: A supported browser types on this platform.76 Returns:77 Browser executable path.78 """79 supported_browser_types = _GetSupportedBrowserTypes()80 if browser_type not in supported_browser_types:81 raise ValueError('Invalid browser type. Supported values are: %s.' %82 ', '.join(supported_browser_types))83 if sys.platform.startswith('win'):84 return _LocateBrowser_Win(browser_type)85 elif sys.platform == 'darwin':86 return _LocateBrowser_Mac(browser_type)87 else:88 raise NotImplementedError('Unsupported platform')89def _LoadVariations(filename):90 """Reads variations commandline switches from a file.91 Args:92 filename: A file that contains variations commandline switches.93 Returns:94 A list of commandline switches.95 """96 with open(filename, 'r') as f:97 data = f.read().replace('\n', ' ')98 switches = split_variations_cmd.ParseCommandLineSwitchesString(data)99 return ['--%s=%s' % (switch_name, switch_value) for100 switch_name, switch_value in switches.items()]101def _BuildBrowserArgs(user_data_dir, extra_browser_args, variations_args):102 """Builds commandline switches browser runs with.103 Args:104 user_data_dir: A path that is used as user data dir.105 extra_browser_args: A list of extra commandline switches browser runs106 with.107 variations_args: A list of commandline switches that defines the108 variations cmd browser runs with.109 Returns:110 A list of commandline switches.111 """112 # Make sure each run is fresh, but avoid first run setup steps.113 browser_args = [114 '--no-first-run',115 '--no-default-browser-check',116 '--user-data-dir=%s' % user_data_dir,117 ]118 browser_args.extend(extra_browser_args)119 browser_args.extend(variations_args)120 return browser_args121def _RunVariations(browser_path, url, extra_browser_args, variations_args):122 """Launches browser with given variations.123 Args:124 browser_path: Browser executable file.125 url: The webpage URL browser goes to after it launches.126 extra_browser_args: A list of extra commandline switches browser runs127 with.128 variations_args: A list of commandline switches that defines the129 variations cmd browser runs with.130 Returns:131 A set of (returncode, stdout, stderr) from browser subprocess.132 """133 command = [os.path.abspath(browser_path)]134 if url:135 command.append(url)136 tempdir = tempfile.mkdtemp(prefix='bisect_variations_tmp')137 command.extend(_BuildBrowserArgs(user_data_dir=tempdir,138 extra_browser_args=extra_browser_args,139 variations_args=variations_args))140 logging.debug(' '.join(command))141 subproc = subprocess.Popen(142 command, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE)143 stdout, stderr = subproc.communicate()144 shutil.rmtree(tempdir, True)145 return (subproc.returncode, stdout, stderr)146def _AskCanReproduce(exit_status, stdout, stderr):147 """Asks whether running Chrome with given variations reproduces the issue.148 Args:149 exit_status: Chrome subprocess return code.150 stdout: Chrome subprocess stdout.151 stderr: Chrome subprocess stderr.152 Returns:153 One of ['y', 'n', 'r']:154 'y': yes155 'n': no156 'r': retry157 """158 # Loop until we get a response that we can parse.159 while True:160 response = raw_input('Can we reproduce with given variations file '161 '[(y)es/(n)o/(r)etry/(s)tdout/(q)uit]: ').lower()162 if response in ('y', 'n', 'r'):163 return response164 if response == 'q':165 sys.exit()166 if response == 's':167 logging.info(stdout)168 logging.info(stderr)169def Bisect(browser_type, url, extra_browser_args, variations_file, output_dir):170 """Bisect variations interactively.171 Args:172 browser_type: One of the supported browser type on this platform. See173 --help for the list.174 url: The webpage URL browser launches with.175 extra_browser_args: A list of commandline switches browser runs with.176 variations_file: A file contains variations commandline switches that177 need to be bisected.178 output_dir: A folder where intermediate bisecting data are stored.179 """180 browser_path = _LocateBrowser(browser_type)181 runs = [variations_file]182 while runs:183 run = runs[0]184 print 'Run Chrome with variations file', run185 variations_args = _LoadVariations(run)186 exit_status, stdout, stderr = _RunVariations(187 browser_path=browser_path, url=url,188 extra_browser_args=extra_browser_args,189 variations_args=variations_args)190 answer = _AskCanReproduce(exit_status, stdout, stderr)191 if answer == 'y':192 runs = split_variations_cmd.SplitVariationsCmdFromFile(run, output_dir)193 if len(runs) == 1:194 # Can divide no further.195 print 'Bisecting succeeded:', ' '.join(variations_args)196 return197 elif answer == 'n':198 if len(runs) == 1:199 raise Exception('Bisecting failed: should reproduce but did not: %s' %200 ' '.join(variations_args))201 runs = runs[1:]202 else:203 assert answer == 'r'204def main():205 parser = optparse.OptionParser()206 parser.add_option("--browser",207 help="select which browser to run. Options include: %s."208 " By default, stable is selected." %209 ", ".join(_GetSupportedBrowserTypes()))210 parser.add_option("-v", "--verbose", action="store_true", default=False,211 help="print out debug information.")212 parser.add_option("--extra-browser-args",213 help="specify extra command line switches for the browser "214 "that are separated by spaces (quoted).")215 parser.add_option("--url",216 help="specify the webpage URL the browser launches with. "217 "This is optional.")218 parser.add_option("--input-file",219 help="specify the filename that contains variations cmd "220 "to bisect. This has to be specified.")221 parser.add_option("--output-dir",222 help="specify a folder where output files are saved. "223 "If not specified, it is the folder of the input file.")224 options, _ = parser.parse_args()225 if options.verbose:226 logging.basicConfig(level=logging.DEBUG)227 if options.input_file is None:228 raise ValueError('Missing input through --input-file.')229 output_dir = options.output_dir230 if output_dir is None:231 output_dir, _ = os.path.split(options.input_file)232 if not os.path.exists(output_dir):233 os.makedirs(output_dir)234 browser_type = options.browser235 if browser_type is None:236 browser_type = 'stable'237 extra_browser_args = []238 if options.extra_browser_args is not None:239 extra_browser_args = options.extra_browser_args.split()240 Bisect(browser_type=browser_type, url=options.url,241 extra_browser_args=extra_browser_args,242 variations_file=options.input_file, output_dir=output_dir)243 return 0244if __name__ == '__main__':...
browser.py
Source:browser.py
1# -*- coding:UTF-8 -*-2"""3æµè§å¨æ°æ®ç¸å
³ç±»4@author: hikaru5email: hikaru870806@hotmail.com6å¦æé®é¢æ建议请èç³»7"""8import os9import platform10import sqlite311if platform.system() == "Windows":12 import win32crypt13from common import output14BROWSER_TYPE_IE = 115BROWSER_TYPE_FIREFOX = 216BROWSER_TYPE_CHROME = 317# æ ¹æ®æµè§å¨åæä½ç³»ç»ï¼è¿åæµè§å¨ç¨åºæ件æå¨çè·¯å¾18def get_default_browser_application_path(browser_type):19 if platform.system() != "Windows":20 return None21 if browser_type == BROWSER_TYPE_IE:22 return os.path.abspath(os.path.join(os.getenv("ProgramFiles"), "Internet Explorer\\iexplore.exe"))23 elif browser_type == BROWSER_TYPE_FIREFOX:24 return os.path.abspath(os.path.join(os.getenv("ProgramFiles"), "Mozilla Firefox\\firefox.exe"))25 elif browser_type == BROWSER_TYPE_CHROME:26 return os.path.abspath(os.path.join(os.getenv("ProgramFiles"), "Google\\Chrome\\Application\\chrome.exe"))27 else:28 output.print_msg("ä¸æ¯æçæµè§å¨ç±»åï¼" + browser_type)29 return None30# æ ¹æ®æµè§å¨åæä½ç³»ç»ï¼èªå¨æ¥æ¾é»è®¤æµè§å¨cookieè·¯å¾(åªæ¯æwindows)31def get_default_browser_cookie_path(browser_type):32 if platform.system() != "Windows":33 return None34 if browser_type == BROWSER_TYPE_IE:35 return os.path.join(os.getenv("APPDATA"), "Microsoft\\Windows\\Cookies")36 elif browser_type == BROWSER_TYPE_FIREFOX:37 default_browser_path = os.path.join(os.getenv("APPDATA"), "Mozilla\\Firefox\\Profiles")38 for dir_name in os.listdir(default_browser_path):39 sub_path = os.path.join(default_browser_path, dir_name)40 if os.path.isdir(sub_path):41 if os.path.exists(os.path.join(sub_path, "cookies.sqlite")):42 return os.path.abspath(sub_path)43 elif browser_type == BROWSER_TYPE_CHROME:44 return os.path.abspath(os.path.join(os.getenv("LOCALAPPDATA"), "Google\\Chrome\\User Data\\Default"))45 else:46 output.print_msg("ä¸æ¯æçæµè§å¨ç±»åï¼" + browser_type)47 return None48# ä»æµè§å¨ä¿åçcookiesä¸è·åæå®keyçcookie value49def get_cookie_value_from_browser(cookie_key, file_path, browser_type, target_domains=""):50 if not os.path.exists(file_path):51 output.print_msg("cookieç®å½ï¼" + file_path + " ä¸åå¨")52 return None53 if browser_type == BROWSER_TYPE_IE:54 for cookie_name in os.listdir(file_path):55 if cookie_name.find(".txt") == -1:56 continue57 with open(os.path.join(file_path, cookie_name), "r") as cookie_file:58 cookie_info = cookie_file.read()59 for cookies in cookie_info.split("*"):60 cookie_list = cookies.strip("\n").split("\n")61 if len(cookie_list) < 8:62 continue63 domain = cookie_list[2].split("/")[0]64 if _filter_domain(domain, target_domains):65 continue66 if cookie_list[0] == cookie_key:67 return cookie_list[1]68 elif browser_type == BROWSER_TYPE_FIREFOX:69 con = sqlite3.connect(os.path.join(file_path, "cookies.sqlite"))70 cur = con.cursor()71 cur.execute("select host, path, name, value from moz_cookies")72 for cookie_info in cur.fetchall():73 domain = cookie_info[0]74 if _filter_domain(domain, target_domains):75 continue76 if cookie_info[2] == cookie_key:77 return cookie_info[3]78 elif browser_type == BROWSER_TYPE_CHROME:79 # chromeä»
æ¯æwindowsç³»ç»ç解å¯80 if platform.system() != "Windows":81 return None82 con = sqlite3.connect(os.path.join(file_path, "Cookies"))83 cur = con.cursor()84 cur.execute("select host_key, path, name, value, encrypted_value from cookies")85 for cookie_info in cur.fetchall():86 domain = cookie_info[0]87 if _filter_domain(domain, target_domains):88 continue89 if cookie_info[2] == cookie_key:90 try:91 value = win32crypt.CryptUnprotectData(cookie_info[4], None, None, None, 0)[1]92 except:93 return None94 return value95 else:96 output.print_msg("ä¸æ¯æçæµè§å¨ç±»åï¼" + browser_type)97 return None98 return None99# æ¯å¦éè¦è¿æ»¤è¿ä¸ªåçcookie100# return True - è¿æ»¤ï¼ä¸éè¦å è½½101# return False - ä¸è¿æ»¤ï¼éè¦å è½½102def _filter_domain(domain, target_domains):103 if target_domains:104 if isinstance(target_domains, str):105 if domain.find(target_domains) >= 0:106 return False107 else:108 for target_domain in target_domains:109 if domain.find(target_domain) >= 0:110 return False111 return True112 else:113 return False114# ä»æµè§å¨ä¿åçcookieæ件ä¸è¯»åææcookie115# return {116# "domain1": {"key1": "value1", "key2": "value2", ......}117# "domain2": {"key1": "value1", "key2": "value2", ......}118# }119def get_all_cookie_from_browser(browser_type, file_path):120 if not os.path.exists(file_path):121 output.print_msg("cookieç®å½ï¼" + file_path + " ä¸åå¨")122 return None123 all_cookies = {}124 if browser_type == 1:125 for cookie_name in os.listdir(file_path):126 if cookie_name.find(".txt") == -1:127 continue128 with open(os.path.join(file_path, cookie_name), "r") as cookie_file:129 cookie_info = cookie_file.read()130 for cookies in cookie_info.split("*"):131 cookie_list = cookies.strip("\n").split("\n")132 if len(cookie_list) < 8:133 continue134 cookie_domain = cookie_list[2].split("/")[0]135 cookie_key = cookie_list[0]136 cookie_value = cookie_list[1]137 if cookie_domain not in all_cookies:138 all_cookies[cookie_domain] = {}139 all_cookies[cookie_domain][cookie_key] = cookie_value140 elif browser_type == 2:141 con = sqlite3.connect(os.path.join(file_path, "cookies.sqlite"))142 cur = con.cursor()143 cur.execute("select host, path, name, value from moz_cookies")144 for cookie_info in cur.fetchall():145 cookie_domain = cookie_info[0]146 cookie_key = cookie_info[2]147 cookie_value = cookie_info[3]148 if cookie_domain not in all_cookies:149 all_cookies[cookie_domain] = {}150 all_cookies[cookie_domain][cookie_key] = cookie_value151 elif browser_type == 3:152 # chromeä»
æ¯æwindowsç³»ç»ç解å¯153 if platform.system() != "Windows":154 return None155 con = sqlite3.connect(os.path.join(file_path, "Cookies"))156 cur = con.cursor()157 cur.execute("select host_key, path, name, value, encrypted_value from cookies")158 for cookie_info in cur.fetchall():159 cookie_domain = cookie_info[0]160 cookie_key = cookie_info[2]161 try:162 cookie_value = win32crypt.CryptUnprotectData(cookie_info[4], None, None, None, 0)[1]163 except:164 continue165 if cookie_domain not in all_cookies:166 all_cookies[cookie_domain] = {}167 all_cookies[cookie_domain][cookie_key] = cookie_value168 else:169 output.print_msg("ä¸æ¯æçæµè§å¨ç±»åï¼" + browser_type)170 return None...
test.py
Source:test.py
1from selenium import webdriver2from selenium.webdriver.common.by import By3from selenium.webdriver.common.keys import Keys4from selenium.webdriver.support.ui import WebDriverWait5from selenium.webdriver.support import expected_conditions as EC6from selenium.common.exceptions import NoSuchElementException7from selenium.common.exceptions import ElementNotVisibleException8from selenium.common.exceptions import ElementNotSelectableException9from unittest import TestCase10import time11import os12import platform13import sys14import datetime15import re16import unittest17def log(message):18 script_name = sys.argv[0]19 print(str(datetime.datetime.now()) + '\t' + script_name + '\t' + message)20def log_exception(message):21 log(message + ' : ' + str(sys.exc_info()22 [0]) + ' : ' + str(sys.exc_info()[1]))23browsers = [ 'Firefox', 'Chrome', 'Edge', 'Safari' ]24urls = [ 'https://slhpa-03.appspot.com/slhpa/', 'https://slhpa-06.appspot.com/slhpa/', 'http://127.0.0.1:8000/slhpa/' ]25class Tester(TestCase):26 driver = None27 wait = None28 def check_row_count(self, url, c, browser_type):29 if browser_type != "Chrome":30 time.sleep(4) # :( :( :(31 rows = self.driver.find_elements(By.XPATH, "//tr")32 log("found " + str(len(rows)) + " on " + url)33 if c + 1 != len(rows):34 print('x') # for debugging only.35 self.assertEqual(c + 1, len(rows)) # header row plus c data rows.36 def extract_count(self, index):37 search_result_count = self.driver.find_element(38 By.XPATH, "//span[contains(text(),'Search matches: ')]")39 p = re.compile(r'\d+')40 m = p.findall(search_result_count.text)41 return int(m[index])42 def verify_search(self, browser_type):43 total_records = self.extract_count(1)44 search_field = self.driver.find_element_by_id('id_search_term')45 search_field.send_keys('Estudillo')46 search_button = self.driver.find_element(47 By.XPATH, "//button[contains(text(),'Search')]")48 search_button.send_keys(Keys.ENTER)49 if browser_type != "Chrome":50 time.sleep(3) # :( :( :(51 searched_records = self.extract_count(0)52 self.assertGreater(searched_records, 0, browser_type)53 self.assertLess(searched_records, total_records, browser_type)54 def verify_photo(self):55 # TODO : only checks if src attribute exists. Must be expanded to see if img file is actually there.56 images = self.driver.find_elements(By.XPATH, "//img")57 self.assertIsNotNone(images)58 for image in images:59 src = image.get_attribute("src")60 if '00000001.jpg' in src:61 return62 self.assertTrue(False, 'No img with 00000001.jpg src.')63 64 def run_base_test(self, url, browser_type):65 self.driver.get(url)66 time.sleep(2)67 edit_field = self.driver.find_elements(By.XPATH, "//*[@id=\"id_resource_name__contains\"]")68 self.assertIsNot(edit_field, None)69 if 'https://slhpa-06.appspot.com/slhpa/' in url:70 self.check_row_count(url, 0, browser_type)71 else:72 self.check_row_count(url, 10, browser_type)73 set_to_25 = self.driver.find_element(By.XPATH, "//*[@id=\"id_records_per_page\"]/option[2]")74 set_to_25.click()75 self.check_row_count(url, 25, browser_type)76 self.verify_photo()77 # If we ever want to automate search testing in old listview,78 # we must write a completely separate function.79 if not 'old/' in url:80 self.verify_search(browser_type)81 def run_view_test(self, url, browser_type):82 self.run_base_test(url, browser_type)83 def run_edit_test(self, url):84 add_new = self.driver.find_element(85 By.XPATH, "//a[contains(text(),'Add new photo record')]")86 if add_new:87 self.assertTrue('https://slhpa-06.appspot.com/slhpa/' in url or 'http://127.0.0.1:8000/slhpa/' in url)88 def set_web_driver(self, browser_type):89 if browser_type == 'Chrome':90 self.driver = webdriver.Chrome()91 else:92 if browser_type == 'Firefox':93 self.driver = webdriver.Firefox()94 else:95 if browser_type == 'Edge':96 self.driver = webdriver.Edge()97 else:98 if browser_type == 'Safari':99 self.driver = webdriver.Safari()100 else:101 raise "Unknown browser_type: " + browser_type102 def run_test(self, url, run_all_tests, browser_type):103 time.sleep(3)104 self.wait = WebDriverWait(self.driver, 10, poll_frequency=1,105 ignored_exceptions=[NoSuchElementException,106 ElementNotVisibleException,107 ElementNotSelectableException])108 # Implicit wait - tells web driver to poll the DOM for specified time;109 # wait is set for duration of web driver object.110 self.driver.implicitly_wait(2)111 self.run_view_test(url, browser_type)112 if run_all_tests:113 self.run_edit_test(url)114 def run_local_tests(self, browser_type):115 if 'http://127.0.0.1:8000/slhpa/' in urls:116 self.run_test('http://127.0.0.1:8000/slhpa/', True, browser_type)117 if 'http://127.0.0.1:8000/slhpa/old/' in urls:118 self.run_test('http://127.0.0.1:8000/slhpa/old/', True, browser_type)119 def run_gcp_tests(self, browser_type):120 if 'https://slhpa-03.appspot.com/slhpa/' in urls:121 self.run_test('https://slhpa-03.appspot.com/slhpa/', False, browser_type)122 if 'https://slhpa-03.appspot.com/slhpa/old/' in urls:123 self.run_test('https://slhpa-03.appspot.com/slhpa/old/', False, browser_type)124 if 'https://slhpa-06.appspot.com/slhpa/' in urls:125 self.run_test('https://slhpa-06.appspot.com/slhpa/', True, browser_type)126 def test_by_browser(self):127 for browser_type in browsers:128 if platform.system() == 'Windows' and browser_type == 'Safari':129 continue130 if platform.system() == 'Darwin' and browser_type == 'Edge':131 continue132 try:133 self.set_web_driver(browser_type)134 self.run_local_tests(browser_type)135 self.run_gcp_tests(browser_type)136 finally:137 self.driver.close()138if __name__ == '__main__':139 browsers = [ "Chrome" ]140 urls = [ 'http://127.0.0.1:8000/slhpa/',141 'https://slhpa-03.appspot.com/slhpa/',142 'http://127.0.0.1:8000/slhpa/old/',143 'https://slhpa-03.appspot.com/slhpa/old/' ]144 unittest.main()...
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.
Get 100 minutes of automation test minutes FREE!!