Best Python code snippet using playwright-python
biu.py
Source:biu.py
...59 #print("93", dialog.message)60 dialog.dismiss()61# def test_css():62# #print("add_style_tag")63# page.add_style_tag(content=".focusClass {border:10px solid #FE0000;}")64# page.add_script_tag(content='<script>console.log("111111111111111111111111")</script>')65def initPage(pageConfig=None, browser=None):66 if not browser:67 browser = initBrowser()68 # å建é身çªå£69 context = browser.new_context(70 http_credentials={"username": "admin", "password": "Redhat@2015"})71 context.tracing.start(screenshots=True, snapshots=True)72 page = context.new_page()73 page.add_style_tag(content=".focusClass {border:10px solid #FE0000;}")74 # page.add_init_script(path="./dom_monitoring.js")75 # page.on("dialog", handle_dialog)76 # page.expose_function("getlink", getlink)77 # page.expose_function("test_css", test_css)78 if pageConfig:79 if "pageLoadTimeout" in pageConfig:80 curPageLoadTimeout = pageConfig["pageLoadTimeout"]81 curPageLoadTimeoutMilliSec = curPageLoadTimeout * 100082 page.set_default_navigation_timeout(curPageLoadTimeoutMilliSec)83 page.set_default_timeout(curPageLoadTimeoutMilliSec)84 return page, context85def closeBrowser(browser):86 browser.close()87def firstOpen(target):88 page = initPage(browser=browser)89 page.goto(target, wait_until="networkidle", timeout=600000)90# def tagFocus(page):91# page.evaluate('''() => {92# function focusInput() {93# console.log("注å
¥äºtagFocus jsèæ¬")94# var elements = document.querySelectorAll("input,span,a,link,select,textarea");95# console.log(elements);96# for (var i=0; i < elements.length; i++) {97# elements[i].onfocus = function() { this.className = 'focusClass'; };98# elements[i].onblur = function() { this.className = ''; };99# }100# }101# setTimeout(function() {102# focusInput()103# }, 100);104# }''')105class crawlTar:106 def __init__(self, page, tarurl):107 self.page = page108 self.target = tarurl109 self.js_content_list = [] # 对已ç»è§¦åè¿çtagææ ï¼é²æ¢éå¤ç¹å»110 self.req_list = [] # å·²ç»è¯·æ±è¿çé¾æ¥ï¼éå¤ç请æ±ä¸åæ¶é111 self.url_list = [] # å¿äº112 self.q = Queue(maxsize=0) # ä»»å¡éå113 self.wbk = xlwt.Workbook() # åå§åworkbook对象114 self.sheet = self.wbk.add_sheet('My_Worksheet') # å建表115 self.sheet.write(0, 0, "é¾æ¥")116 self.sheet.write(0, 1, "请æ±æ¹å¼")117 self.sheet.write(0, 2, "headers头")118 self.sheet.write(0, 3, "dataæ°æ®")119 self.page.on("request", lambda request: self.handle_request(request))120 # self.page.on("console", lambda msg: self.echo_console(msg))121 self.page.on("dialog", lambda dialog: dialog.accept())122 # æ 注é¾æ¥åæ¥æº123 n = 0124 def getlink(self, link, source):125 # #print("ãä¿®å¤åãè·åå°çé¾æ¥ä¸º:\t", link, "\t", source)126 new_url = self.repair_url(link)127 # #print("ãä¿®å¤åãè·åå°çé¾æ¥ä¸º:\t", new_url, "\t", source)128 tarurl_domain = urlparse(self.target).netloc129 url_domain = urlparse(new_url).netloc130 # #print(tarurl_domain, url_domain)131 # å¦ææ¯ååç132 if tarurl_domain == url_domain:133 if self.parse_link_static(new_url):134 pass135 else:136 getlinkdict = {}137 getlinkdict["url"] = new_url138 getlinkdict["source"] = source139 # #print(getlinkdict, "\tvvvvvsssss\t", self.url_list)140 if new_url in self.url_list:141 pass142 else:143 #print("ãååã:\t", new_url, "\t", source)144 self.url_list.append(new_url)145 logger.info("request\t>>>\t{}".format(new_url))146 self.q.put(new_url)147 def echo_console(self, msg):148 if "Error" in msg.text or "Failed" in msg.text:149 pass150 else:151 print("console info:\t", msg.text)152 def handle_request(self, request):153 req_data = {}154 # print(request.url)155 # #print("handle_request:\t", request.url, request.method)156 # #print("å½å请æ±:\t", request.url, "\tvs\t", "ç½é¡µè¾å
¥æ :\t", self.page.url)157 if request.is_navigation_request() and not self.page.frames[0].parent_frame:158 # self.page.route(request.url,lambda route: route.fulfill(159 # status=204160 # ))161 # print("handle_navigation:\t", request.url)162 self.getlink(request.url, "handle_navigation")163 else:164 self.getlink(request.url, "handle_request")165 # if is_target(request.url, tarurl):166 # if parse_link_static(request.url) == False:167 # n = n + 1168 # sheet.write(n, 0, request.url)169 # sheet.write(n, 1, request.method)170 # sheet.write(n, 2, json.dumps(request.headers))171 # sheet.write(n, 3, json.dumps(request.post_data))172 # q.put(request.url)173 req_data["url"] = request.url174 req_data["method"] = request.method175 req_data["headers"] = request.headers176 if request.post_data:177 req_data["body_data"] = request.post_data178 else:179 req_data["body_data"] = ""180 # æåå°ç»æåå
¥excle181 for i in self.req_list:182 if request.url == i["url"] and request.method == i["method"]:183 pass184 185 if self.set_req_list(request):186 # print(request.url,"\n",req_data,"\n",self.req_list)187 self.req_list.append(req_data)188 def set_req_list(self,request):189 for i in self.req_list:190 if request.url == i["url"] and request.method == i["method"]:191 return False192 return True193 def test_css(self):194 #print("add_style_tag")195 self.page.add_style_tag(196 content=".focusClass {border:2px solid #FF0400;outline:none}")197 self.page.add_script_tag(198 content='console.log("111111111111111111111111")')199 def repair_url(self, url):200 tarurl_domain = urlparse(self.target).netloc201 tarurl_scheme = urlparse(self.target).scheme202 url_domain = urlparse(url).netloc203 # å¤ææ¯å¦ä¸ºå®æ´é¾æ¥204 new_url = ""205 if "http://" in url or "https://" in url:206 return url207 else:208 new_url = tarurl_scheme + "://" + tarurl_domain + url209 return new_url...
test_page.py
Source:test_page.py
...476 await page.add_script_tag(url=url)477 assert url in exc_info.value.message478async def test_add_style_tag_should_work_with_a_url(page, server):479 await page.goto(server.EMPTY_PAGE)480 style_handle = await page.add_style_tag(url="/injectedstyle.css")481 assert style_handle.as_element()482 assert (483 await page.evaluate(484 "window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"485 )486 == "rgb(255, 0, 0)"487 )488async def test_add_style_tag_should_throw_an_error_if_loading_from_url_fail(489 page, server490):491 await page.goto(server.EMPTY_PAGE)492 with pytest.raises(Error) as exc_info:493 await page.add_style_tag(url="/nonexistfile.js")494 assert exc_info.value495async def test_add_style_tag_should_work_with_a_path(page, server, assetdir):496 await page.goto(server.EMPTY_PAGE)497 style_handle = await page.add_style_tag(path=assetdir / "injectedstyle.css")498 assert style_handle.as_element()499 assert (500 await page.evaluate(501 "window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"502 )503 == "rgb(255, 0, 0)"504 )505async def test_add_style_tag_should_include_source_url_when_path_is_provided(506 page, server, assetdir507):508 await page.goto(server.EMPTY_PAGE)509 await page.add_style_tag(path=assetdir / "injectedstyle.css")510 style_handle = await page.query_selector("style")511 style_content = await page.evaluate("style => style.innerHTML", style_handle)512 assert os.path.join("assets", "injectedstyle.css") in style_content513async def test_add_style_tag_should_work_with_content(page, server):514 await page.goto(server.EMPTY_PAGE)515 style_handle = await page.add_style_tag(content="body { background-color: green; }")516 assert style_handle.as_element()517 assert (518 await page.evaluate(519 "window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')"520 )521 == "rgb(0, 128, 0)"522 )523async def test_add_style_tag_should_throw_when_added_with_content_to_the_CSP_page(524 page, server525):526 await page.goto(server.PREFIX + "/csp.html")527 with pytest.raises(Error) as exc_info:528 await page.add_style_tag(content="body { background-color: green; }")529 assert exc_info.value530async def test_add_style_tag_should_throw_when_added_with_URL_to_the_CSP_page(531 page, server532):533 await page.goto(server.PREFIX + "/csp.html")534 with pytest.raises(Error) as exc_info:535 await page.add_style_tag(url=server.CROSS_PROCESS_PREFIX + "/injectedstyle.css")536 assert exc_info.value537async def test_url_should_work(page, server):538 assert page.url == "about:blank"539 await page.goto(server.EMPTY_PAGE)540 assert page.url == server.EMPTY_PAGE541async def test_url_should_include_hashes(page, server):542 await page.goto(server.EMPTY_PAGE + "#hash")543 assert page.url == server.EMPTY_PAGE + "#hash"544 await page.evaluate("window.location.hash = 'dynamic'")545 assert page.url == server.EMPTY_PAGE + "#dynamic"546async def test_title_should_return_the_page_title(page, server):547 await page.goto(server.PREFIX + "/title.html")548 assert await page.title() == "Woof-Woof"549async def test_select_option_should_select_single_option(page, server):...
_page.py
Source:_page.py
...362 content: str = None,363 type: str = None,364 ) -> ElementHandle:365 return await self._main_frame.add_script_tag(**locals_to_params(locals()))366 async def add_style_tag(367 self, url: str = None, path: Union[str, Path] = None, content: str = None368 ) -> ElementHandle:369 return await self._main_frame.add_style_tag(**locals_to_params(locals()))370 async def expose_function(self, name: str, callback: Callable) -> None:371 await self.expose_binding(name, lambda source, *args: callback(*args))372 async def expose_binding(373 self, name: str, callback: Callable, handle: bool = None374 ) -> None:375 if name in self._bindings:376 raise Error(f'Function "{name}" has been already registered')377 if name in self._browser_context._bindings:378 raise Error(379 f'Function "{name}" has been already registered in the browser context'380 )381 self._bindings[name] = callback382 await self._channel.send(383 "exposeBinding", dict(name=name, needsHandle=handle or False)...
_frame.py
Source:_frame.py
...301 with open(path, "r") as file:302 params["content"] = file.read() + "\n//# sourceURL=" + str(Path(path))303 del params["path"]304 return from_channel(await self._channel.send("addScriptTag", params))305 async def add_style_tag(306 self, url: str = None, path: Union[str, Path] = None, content: str = None307 ) -> ElementHandle:308 params = locals_to_params(locals())309 if path:310 with open(path, "r") as file:311 params["content"] = (312 file.read() + "\n/*# sourceURL=" + str(Path(path)) + "*/"313 )314 del params["path"]315 return from_channel(await self._channel.send("addStyleTag", params))316 async def click(317 self,318 selector: str,319 modifiers: List[KeyboardModifier] = None,...
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!!