How to use add_style_tag method in Playwright Python

Best Python code snippet using playwright-python

biu.py

Source:biu.py Github

copy

Full Screen

...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...

Full Screen

Full Screen

test_page.py

Source:test_page.py Github

copy

Full Screen

...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):...

Full Screen

Full Screen

_page.py

Source:_page.py Github

copy

Full Screen

...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)...

Full Screen

Full Screen

_frame.py

Source:_frame.py Github

copy

Full Screen

...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,...

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