How to use test_sync_query_selector method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_sync.py

Source: test_sync.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License")
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import os
16
17import pytest
18
19from playwright.sync_api import Browser, Error, Page, TimeoutError, sync_playwright
20
21
22def test_sync_query_selector(page):
23    page.set_content(
24        """
25    <h1 id="foo">Bar</h1>
26    """
27    )
28    assert (
29        page.query_selector("#foo").inner_text()
30        == page.query_selector("h1").inner_text()
31    )
32
33
34def test_sync_click(page):
35    page.set_content(
36        """
37    <button onclick="window.clicked=true">Bar</button>
38    """
39    )
40    page.click("text=Bar")
41    assert page.evaluate("()=>window.clicked")
42
43
44def test_sync_nested_query_selector(page):
45    page.set_content(
46        """
47    <div id="one">
48        <span class="two">
49            <label>
50                MyValue
51            </label>
52        </span>
53    </div>
54    """
55    )
56    e1 = page.query_selector("#one")
57    e2 = e1.query_selector(".two")
58    e3 = e2.query_selector("label")
59    assert e3.inner_text() == "MyValue"
60
61
62def test_sync_handle_multiple_pages(context):
63    page1 = context.new_page()
64    page2 = context.new_page()
65    assert len(context.pages) == 2
66    page1.set_content("one")
67    page2.set_content("two")
68    assert "one" in page1.content()
69    assert "two" in page2.content()
70    page1.close()
71    assert len(context.pages) == 1
72    page2.close()
73    assert len(context.pages) == 0
74    for page in [page1, page2]:
75        with pytest.raises(Error):
76            page.content()
77
78
79def test_sync_wait_for_event(page: Page, server):
80    with page.expect_event("popup", timeout=10000) as popup:
81        page.evaluate("(url) => window.open(url)", server.EMPTY_PAGE)
82    assert popup.value
83
84
85def test_sync_wait_for_event_raise(page):
86    with pytest.raises(Error):
87        with page.expect_event("popup", timeout=500) as popup:
88            assert False
89        assert popup.value is None
90
91
92def test_sync_make_existing_page_sync(page):
93    page = page
94    assert page.evaluate("() => ({'playwright': true})") == {"playwright": True}
95    page.set_content("<h1>myElement</h1>")
96    page.wait_for_selector("text=myElement")
97
98
99def test_sync_network_events(page, server):
100    server.set_route(
101        "/hello-world",
102        lambda request: (
103            request.setHeader("Content-Type", "text/plain"),
104            request.write(b"Hello world"),
105            request.finish(),
106        ),
107    )
108    page.goto(server.EMPTY_PAGE)
109    messages = []
110    page.on(
111        "request", lambda request: messages.append(f">>{request.method}{request.url}")
112    )
113    page.on(
114        "response",
115        lambda response: messages.append(f"<<{response.status}{response.url}"),
116    )
117    response = page.evaluate("""async ()=> (await fetch("/hello-world")).text()""")
118    assert response == "Hello world"
119    assert messages == [
120        f">>GET{server.PREFIX}/hello-world",
121        f"<<200{server.PREFIX}/hello-world",
122    ]
123
124
125def test_console_should_work(page):
126    messages = []
127    page.once("console", lambda m: messages.append(m))
128    page.evaluate('() => console.log("hello", 5, {foo: "bar"})'),
129    assert len(messages) == 1
130    message = messages[0]
131    assert message.text == "hello 5 [email protected]"
132    assert str(message) == "hello 5 [email protected]"
133    assert message.type == "log"
134    assert message.args[0].json_value() == "hello"
135    assert message.args[1].json_value() == 5
136    assert message.args[2].json_value() == {"foo": "bar"}
137
138
139def test_sync_download(browser: Browser, server):
140    server.set_route(
141        "/downloadWithFilename",
142        lambda request: (
143            request.setHeader("Content-Type", "application/octet-stream"),
144            request.setHeader("Content-Disposition", "attachment; filename=file.txt"),
145            request.write(b"Hello world"),
146            request.finish(),
147        ),
148    )
149    page = browser.new_page(accept_downloads=True)
150    page.set_content(f'<a href="{server.PREFIX}/downloadWithFilename">download</a>')
151
152    with page.expect_event("download") as download:
153        page.click("a")
154    assert download.value
155    assert download.value.suggested_filename == "file.txt"
156    path = download.value.path()
157    assert os.path.isfile(path)
158    with open(path, "r") as fd:
159        assert fd.read() == "Hello world"
160    page.close()
161
162
163def test_sync_workers_page_workers(page: Page, server):
164    with page.expect_event("worker") as event_worker:
165        page.goto(server.PREFIX + "/worker/worker.html")
166    assert event_worker.value
167    worker = page.workers[0]
168    assert "worker.js" in worker.url
169
170    assert worker.evaluate('() => self["workerFunction"]()') == "worker function result"
171
172    page.goto(server.EMPTY_PAGE)
173    assert len(page.workers) == 0
174
175
176def test_sync_playwright_multiple_times():
177    with pytest.raises(Error) as exc:
178        with sync_playwright() as pw:
179            assert pw.chromium
180    assert (
181        "It looks like you are using Playwright Sync API inside the asyncio loop."
182        in exc.value.message
183    )
184
185
186def test_sync_set_default_timeout(page):
187    page.set_default_timeout(1)
188    with pytest.raises(TimeoutError) as exc:
189        page.wait_for_function("false")
190    assert "Timeout 1ms exceeded." in exc.value.message
191
192
193def test_close_should_reject_all_promises(context):
194    new_page = context.new_page()
195    with pytest.raises(Error) as exc_info:
196        new_page._gather(
197            lambda: new_page.evaluate("() => new Promise(r => {})"),
198            lambda: new_page.close(),
199        )
200    assert "Protocol error" in exc_info.value.message
201
202
203def test_expect_response_should_work(page: Page, server):
204    with page.expect_response("**/*") as resp:
205        page.goto(server.EMPTY_PAGE)
206    assert resp.value
207    assert resp.value.url == server.EMPTY_PAGE
208    assert resp.value.status == 200
209    assert resp.value.ok
210    assert resp.value.request
211
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)