Best Python code snippet using playwright-python
test_page.py
Source: test_page.py
...402 await page.set_content("<div>\n</div>")403 assert await page.eval_on_selector("div", "div => div.textContent") == "\n"404async def test_add_script_tag_should_work_with_a_url(page, server):405 await page.goto(server.EMPTY_PAGE)406 script_handle = await page.add_script_tag(url="/injectedfile.js")407 assert script_handle.as_element()408 assert await page.evaluate("__injected") == 42409async def test_add_script_tag_should_work_with_a_url_and_type_module(page, server):410 await page.goto(server.EMPTY_PAGE)411 await page.add_script_tag(url="/es6/es6import.js", type="module")412 assert await page.evaluate("__es6injected") == 42413async def test_add_script_tag_should_work_with_a_path_and_type_module(414 page, server, assetdir415):416 await page.goto(server.EMPTY_PAGE)417 await page.add_script_tag(path=assetdir / "es6" / "es6pathimport.js", type="module")418 await page.wait_for_function("window.__es6injected")419 assert await page.evaluate("__es6injected") == 42420async def test_add_script_tag_should_work_with_a_content_and_type_module(page, server):421 await page.goto(server.EMPTY_PAGE)422 await page.add_script_tag(423 content="import num from '/es6/es6module.js';window.__es6injected = num;",424 type="module",425 )426 await page.wait_for_function("window.__es6injected")427 assert await page.evaluate("__es6injected") == 42428async def test_add_script_tag_should_throw_an_error_if_loading_from_url_fail(429 page, server430):431 await page.goto(server.EMPTY_PAGE)432 with pytest.raises(Error) as exc_info:433 await page.add_script_tag(url="/nonexistfile.js")434 assert exc_info.value435async def test_add_script_tag_should_work_with_a_path(page, server, assetdir):436 await page.goto(server.EMPTY_PAGE)437 script_handle = await page.add_script_tag(path=assetdir / "injectedfile.js")438 assert script_handle.as_element()439 assert await page.evaluate("__injected") == 42440@pytest.mark.skip_browser("webkit")441async def test_add_script_tag_should_include_source_url_when_path_is_provided(442 page, server, assetdir443):444 # Lacking sourceURL support in WebKit445 await page.goto(server.EMPTY_PAGE)446 await page.add_script_tag(path=assetdir / "injectedfile.js")447 result = await page.evaluate("__injectedError.stack")448 assert os.path.join("assets", "injectedfile.js") in result449async def test_add_script_tag_should_work_with_content(page, server):450 await page.goto(server.EMPTY_PAGE)451 script_handle = await page.add_script_tag(content="window.__injected = 35;")452 assert script_handle.as_element()453 assert await page.evaluate("__injected") == 35454@pytest.mark.skip_browser("firefox")455async def test_add_script_tag_should_throw_when_added_with_content_to_the_csp_page(456 page, server457):458 # Firefox fires onload for blocked script before it issues the CSP console error.459 await page.goto(server.PREFIX + "/csp.html")460 with pytest.raises(Error) as exc_info:461 await page.add_script_tag(content="window.__injected = 35;")462 assert exc_info.value463async def test_add_script_tag_should_throw_when_added_with_URL_to_the_csp_page(464 page, server465):466 await page.goto(server.PREFIX + "/csp.html")467 with pytest.raises(Error) as exc_info:468 await page.add_script_tag(url=server.CROSS_PROCESS_PREFIX + "/injectedfile.js")469 assert exc_info.value470async def test_add_script_tag_should_throw_a_nice_error_when_the_request_fails(471 page, server472):473 await page.goto(server.EMPTY_PAGE)474 url = server.PREFIX + "/this_does_not_exist.js"475 with pytest.raises(Error) as exc_info: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):...
test_browsercontext.py
Source: test_browsercontext.py
...160 context = await browser.new_context()161 page = await context.new_page()162 await page.goto(server.PREFIX + "/csp.html")163 try:164 await page.add_script_tag(content="window.__injected = 42;")165 except Error:166 pass167 assert await page.evaluate("window.__injected") is None168 await context.close()169 await baseline()170 # By-pass CSP and try one more time.171 async def override():172 context = await browser.new_context(bypass_csp=True)173 page = await context.new_page()174 await page.goto(server.PREFIX + "/csp.html")175 await page.add_script_tag(content="window.__injected = 42;")176 assert await page.evaluate("() => window.__injected") == 42177 await context.close()178 await override()179async def test_page_event_should_bypass_csp_header(browser, server):180 # Make sure CSP prohibits add_script_tag.181 server.set_csp("/empty.html", 'default-src "self"')182 async def baseline():183 context = await browser.new_context()184 page = await context.new_page()185 await page.goto(server.EMPTY_PAGE)186 try:187 await page.add_script_tag(content="window.__injected = 42;")188 except Error:189 pass190 assert await page.evaluate("() => window.__injected") is None191 await context.close()192 await baseline()193 # By-pass CSP and try one more time.194 async def override():195 context = await browser.new_context(bypass_csp=True)196 page = await context.new_page()197 await page.goto(server.EMPTY_PAGE)198 await page.add_script_tag(content="window.__injected = 42;")199 assert await page.evaluate("window.__injected") == 42200 await context.close()201 await override()202async def test_page_event_should_bypass_after_cross_process_navigation(browser, server):203 context = await browser.new_context(bypass_csp=True)204 page = await context.new_page()205 await page.goto(server.PREFIX + "/csp.html")206 await page.add_script_tag(content="window.__injected = 42;")207 assert await page.evaluate("window.__injected") == 42208 await page.goto(server.CROSS_PROCESS_PREFIX + "/csp.html")209 await page.add_script_tag(content="window.__injected = 42;")210 assert await page.evaluate("window.__injected") == 42211 await context.close()212async def test_page_event_should_bypass_csp_in_iframes_as_well(browser, server, utils):213 async def baseline():214 # Make sure CSP prohibits add_script_tag in an iframe.215 context = await browser.new_context()216 page = await context.new_page()217 await page.goto(server.EMPTY_PAGE)218 frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")219 try:220 await frame.add_script_tag(content="window.__injected = 42;")221 except Error:222 pass223 assert await frame.evaluate("window.__injected") is None224 await context.close()225 await baseline()226 # By-pass CSP and try one more time.227 async def override():228 context = await browser.new_context(bypass_csp=True)229 page = await context.new_page()230 await page.goto(server.EMPTY_PAGE)231 frame = await utils.attach_frame(page, "frame1", server.PREFIX + "/csp.html")232 try:233 await frame.add_script_tag(content="window.__injected = 42;")234 except Error:235 pass236 assert await frame.evaluate("window.__injected") == 42237 await context.close()238 await override()239async def test_csp_should_work(browser, is_webkit):240 async def baseline():241 context = await browser.new_context(java_script_enabled=False)242 page = await context.new_page()243 await page.goto('data:text/html, <script>var something = "forbidden"</script>')244 with pytest.raises(Error) as exc_info:245 await page.evaluate("something")246 if is_webkit:247 assert "Can't find variable: something" in exc_info.value.message...
test_defaultbrowsercontext.py
Source: test_defaultbrowsercontext.py
...144 assert request.getHeader("user-agent") == "foobar"145async def test_should_support_bypass_csp_option(launch_persistent, server):146 (page, context) = await launch_persistent(bypass_csp=True)147 await page.goto(server.PREFIX + "/csp.html")148 await page.add_script_tag(content="window.__injected = 42;")149 assert await page.evaluate("() => window.__injected") == 42150async def test_should_support_javascript_enabled_option(launch_persistent, is_webkit):151 (page, context) = await launch_persistent(java_script_enabled=False)152 await page.goto('data:text/html, <script>var something = "forbidden"</script>')153 with pytest.raises(Error) as exc:154 await page.evaluate("something")155 if is_webkit:156 assert "Can't find variable: something" in exc.value.message157 else:158 assert "something is not defined" in exc.value.message159async def test_should_support_http_credentials_option(server, launch_persistent):160 (page, context) = await launch_persistent(161 http_credentials={"username": "user", "password": "pass"}162 )...
d3.py
Source: d3.py
...19 path, _ = split(abspath(__file__))20 with open(join(path, name)) as f:21 result = f.read()22 return result23def add_script_tag(source):24 """ wrap the source file in a script tag """25 return """<script src="{}" type="text/javascript"></script>""".format(source)26class D3Object(object):27 """ Base class for d3.js helper classes """28 libs = [] # custom libs (for the page tail)29 styles = [] # custom styles30 css = "" # component specific css31 js = "" # component specific js32 name = property(lambda self: '%s_%s' % (self.__class__.__name__, id(self)))33 ref = property(lambda self: self.name, doc="the reference to the object")34 wrapper = '<div class="dz-d3-vis" id="{}"></div>'35 def __init__(self, data, options=None, **kwargs):36 """ Initialize the d3 object class37 data -- data for the chart...
Playwright auto-scroll to bottom of infinite-scroll page
How to quickly find out if an element exists in a page or not using playwright
Playwright on google colab : Attempt to free invalid pointer 0x29000020c5a0
How to download PDF files with Playwright? (Python)
Playwright: click on element within one/multiple elements using Python
Scraping Google images with Python3 (requests + BeautifulSoup)
How to quickly find out if an element exists in a page or not using playwright
how to get element from a table, to be selected in playwright python
Using Playwright for Python, how do I select an option from a drop down list?
Can't import name 'sync_playwright' from 'playwright.sync_api' on MacOS and ubutunOS
So I found a working solution.
What I did was to combine Javascript with python Playwright code.
I start the setInterval with a timer of 200ms to scroll down on the page with page.evaluate()
and then I follow it up with a python loop that checks every second whether the total height of the page (scroll included) has changed. If it changes it continues to scroll and if it hasn't changed than the scroll is over.
This is what it looks like:
page.evaluate(
"""
var intervalID = setInterval(function () {
var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
}, 200);
"""
)
prev_height = None
while True:
curr_height = page.evaluate('(window.innerHeight + window.scrollY)')
if not prev_height:
prev_height = curr_height
time.sleep(1)
elif prev_height == curr_height:
page.evaluate('clearInterval(intervalID)')
break
else:
prev_height = curr_height
time.sleep(1)
See the below answer using the new mouse.wheel(x, y) feature for an up to date way to scroll using playwright. Combine my answer with his to lessen the need to use JS.
Check out the latest blogs from LambdaTest on this topic:
Ruby is a programming language which is well suitable for web automation. Ruby makes an excellent choice because of its clean syntax, focus on built-in library integrations, and an active community. Another benefit of Ruby is that it also allows other programming languages like Java, Python, etc. to be used in order to automate applications written in any other frameworks. Therefore you can use Selenium Ruby to automate any sort of application in your system and test the results in any type of testing environment
Are you looking to get started with DevOps or willing to shift gears in your professional career by adding DevOps as a skill? If your answer is yes, you have arrived at the right place!
A productive workspace is crucial in crafting code rather than just finding the right IDE. After several generations of IDEs and code editors, Visual Studio Code is considered one of the best web development IDEs used by developers.
The web development industry is growing, and many Best Automated UI Testing Tools are available to test your web-based project to ensure it is bug-free and easily accessible for every user. These tools help you test your web project and make it fully compatible with user-end requirements and needs.
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!!