How to use test_locators_inner_text_should_work 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_locators.py

Source: test_locators.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
16import re
17from typing import Callable
18from urllib.parse import urlparse
19
20import pytest
21
22from playwright._impl._path_utils import get_file_dirname
23from playwright.sync_api import Error, Page, expect
24from tests.server import Server
25
26_dirname = get_file_dirname()
27FILE_TO_UPLOAD = _dirname / ".." / "assets/file-to-upload.txt"
28
29
30def test_locators_click_should_work(page: Page, server: Server) -> None:
31    page.goto(server.PREFIX + "/input/button.html")
32    button = page.locator("button")
33    button.click()
34    assert page.evaluate("window['result']") == "Clicked"
35
36
37def test_locators_click_should_work_with_node_removed(
38    page: Page, server: Server
39) -> None:
40    page.goto(server.PREFIX + "/input/button.html")
41    page.evaluate("delete window['Node']")
42    button = page.locator("button")
43    button.click()
44    assert page.evaluate("window['result']") == "Clicked"
45
46
47def test_locators_click_should_work_for_text_nodes(page: Page, server: Server) -> None:
48    page.goto(server.PREFIX + "/input/button.html")
49    page.evaluate(
50        """() => {
51        window['double'] = false;
52        const button = document.querySelector('button');
53        button.addEventListener('dblclick', event => {
54        window['double'] = true;
55        });
56    }"""
57    )
58    button = page.locator("button")
59    button.dblclick()
60    assert page.evaluate("double") is True
61    assert page.evaluate("result") == "Clicked"
62
63
64def test_locators_should_have_repr(page: Page, server: Server) -> None:
65    page.goto(server.PREFIX + "/input/button.html")
66    button = page.locator("button")
67    button.click()
68    assert (
69        str(button)
70        == f"<Locator frame=<Frame name= url='{server.PREFIX}/input/button.html'> selector='button'>"
71    )
72
73
74def test_locators_get_attribute_should_work(page: Page, server: Server) -> None:
75    page.goto(server.PREFIX + "/dom.html")
76    button = page.locator("#outer")
77    assert button.get_attribute("name") == "value"
78    assert button.get_attribute("foo") is None
79
80
81def test_locators_input_value_should_work(page: Page, server: Server) -> None:
82    page.goto(server.PREFIX + "/dom.html")
83    page.fill("#textarea", "input value")
84    text_area = page.locator("#textarea")
85    assert text_area.input_value() == "input value"
86
87
88def test_locators_inner_html_should_work(page: Page, server: Server) -> None:
89    page.goto(server.PREFIX + "/dom.html")
90    locator = page.locator("#outer")
91    assert locator.inner_html() == '<div id="inner">Text,\nmore text</div>'
92
93
94def test_locators_inner_text_should_work(page: Page, server: Server) -> None:
95    page.goto(server.PREFIX + "/dom.html")
96    locator = page.locator("#inner")
97    assert locator.inner_text() == "Text, more text"
98
99
100def test_locators_text_content_should_work(page: Page, server: Server) -> None:
101    page.goto(server.PREFIX + "/dom.html")
102    locator = page.locator("#inner")
103    assert locator.text_content() == "Text,\nmore text"
104
105
106def test_locators_is_hidden_and_is_visible_should_work(page: Page) -> None:
107    page.set_content("<div>Hi</div><span></span>")
108
109    div = page.locator("div")
110    assert div.is_visible() is True
111    assert div.is_hidden() is False
112
113    span = page.locator("span")
114    assert span.is_visible() is False
115    assert span.is_hidden() is True
116
117
118def test_locators_is_enabled_and_is_disabled_should_work(page: Page) -> None:
119    page.set_content(
120        """
121        <button disabled>button1</button>
122        <button>button2</button>
123        <div>div</div>
124    """
125    )
126
127    div = page.locator("div")
128    assert div.is_enabled() is True
129    assert div.is_disabled() is False
130
131    button1 = page.locator(':text("button1")')
132    assert button1.is_enabled() is False
133    assert button1.is_disabled() is True
134
135    button1 = page.locator(':text("button2")')
136    assert button1.is_enabled() is True
137    assert button1.is_disabled() is False
138
139
140def test_locators_is_editable_should_work(page: Page) -> None:
141    page.set_content(
142        """
143        <input id=input1 disabled><textarea></textarea><input id=input2>
144    """
145    )
146
147    input1 = page.locator("#input1")
148    assert input1.is_editable() is False
149
150    input2 = page.locator("#input2")
151    assert input2.is_editable() is True
152
153
154def test_locators_is_checked_should_work(page: Page) -> None:
155    page.set_content(
156        """
157        <input type='checkbox' checked><div>Not a checkbox</div>
158    """
159    )
160
161    element = page.locator("input")
162    assert element.is_checked() is True
163    element.evaluate("e => e.checked = false")
164    assert element.is_checked() is False
165
166
167def test_locators_all_text_contents_should_work(page: Page) -> None:
168    page.set_content(
169        """
170        <div>A</div><div>B</div><div>C</div>
171    """
172    )
173
174    element = page.locator("div")
175    assert element.all_text_contents() == ["A", "B", "C"]
176
177
178def test_locators_all_inner_texts(page: Page) -> None:
179    page.set_content(
180        """
181        <div>A</div><div>B</div><div>C</div>
182    """
183    )
184
185    element = page.locator("div")
186    assert element.all_inner_texts() == ["A", "B", "C"]
187
188
189def test_locators_should_query_existing_element(page: Page, server: Server) -> None:
190    page.goto(server.PREFIX + "/playground.html")
191    page.set_content(
192        """<html><body><div class="second"><div class="inner">A</div></div></body></html>"""
193    )
194    html = page.locator("html")
195    second = html.locator(".second")
196    inner = second.locator(".inner")
197    assert page.evaluate("e => e.textContent", inner.element_handle()) == "A"
198
199
200def test_locators_evaluate_handle_should_work(page: Page, server: Server) -> None:
201    page.goto(server.PREFIX + "/dom.html")
202    outer = page.locator("#outer")
203    inner = outer.locator("#inner")
204    check = inner.locator("#check")
205    text = inner.evaluate_handle("e => e.firstChild")
206    page.evaluate("1 + 1")
207    assert (
208        str(outer)
209        == f"<Locator frame=<Frame name= url='{server.PREFIX}/dom.html'> selector='#outer'>"
210    )
211    assert (
212        str(inner)
213        == f"<Locator frame=<Frame name= url='{server.PREFIX}/dom.html'> selector='#outer >> #inner'>"
214    )
215    assert str(text) == "[email protected]#text=Text,↵more text"
216    assert (
217        str(check)
218        == f"<Locator frame=<Frame name= url='{server.PREFIX}/dom.html'> selector='#outer >> #inner >> #check'>"
219    )
220
221
222def test_locators_should_query_existing_elements(page: Page) -> None:
223    page.set_content("""<html><body><div>A</div><br/><div>B</div></body></html>""")
224    html = page.locator("html")
225    elements = html.locator("div").element_handles()
226    assert len(elements) == 2
227    result = []
228    for element in elements:
229        result.append(page.evaluate("e => e.textContent", element))
230    assert result == ["A", "B"]
231
232
233def test_locators_return_empty_array_for_non_existing_elements(page: Page) -> None:
234    page.set_content("""<html><body><div>A</div><br/><div>B</div></body></html>""")
235    html = page.locator("html")
236    elements = html.locator("abc").element_handles()
237    assert len(elements) == 0
238    assert elements == []
239
240
241def test_locators_evaluate_all_should_work(page: Page) -> None:
242    page.set_content(
243        """<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>"""
244    )
245    tweet = page.locator(".tweet .like")
246    content = tweet.evaluate_all("nodes => nodes.map(n => n.innerText)")
247    assert content == ["100", "10"]
248
249
250def test_locators_evaluate_all_should_work_with_missing_selector(page: Page) -> None:
251    page.set_content("""<div class="a">not-a-child-div</div><div id="myId"></div""")
252    tweet = page.locator("#myId .a")
253    nodes_length = tweet.evaluate_all("nodes => nodes.length")
254    assert nodes_length == 0
255
256
257def test_locators_hover_should_work(page: Page, server: Server) -> None:
258    page.goto(server.PREFIX + "/input/scrollable.html")
259    button = page.locator("#button-6")
260    button.hover()
261    assert page.evaluate("document.querySelector('button:hover').id") == "button-6"
262
263
264def test_locators_fill_should_work(page: Page, server: Server) -> None:
265    page.goto(server.PREFIX + "/input/textarea.html")
266    button = page.locator("input")
267    button.fill("some value")
268    assert page.evaluate("result") == "some value"
269
270
271def test_locators_check_should_work(page: Page) -> None:
272    page.set_content("<input id='checkbox' type='checkbox'></input>")
273    button = page.locator("input")
274    button.check()
275    assert page.evaluate("checkbox.checked") is True
276
277
278def test_locators_uncheck_should_work(page: Page) -> None:
279    page.set_content("<input id='checkbox' type='checkbox' checked></input>")
280    button = page.locator("input")
281    button.uncheck()
282    assert page.evaluate("checkbox.checked") is False
283
284
285def test_locators_select_option_should_work(page: Page, server: Server) -> None:
286    page.goto(server.PREFIX + "/input/select.html")
287    select = page.locator("select")
288    select.select_option("blue")
289    assert page.evaluate("result.onInput") == ["blue"]
290    assert page.evaluate("result.onChange") == ["blue"]
291
292
293def test_locators_focus_should_work(page: Page, server: Server) -> None:
294    page.goto(server.PREFIX + "/input/button.html")
295    button = page.locator("button")
296    assert button.evaluate("button => document.activeElement === button") is False
297    button.focus()
298    assert button.evaluate("button => document.activeElement === button") is True
299
300
301def test_locators_dispatch_event_should_work(page: Page, server: Server) -> None:
302    page.goto(server.PREFIX + "/input/button.html")
303    button = page.locator("button")
304    button.dispatch_event("click")
305    assert page.evaluate("result") == "Clicked"
306
307
308def test_locators_should_upload_a_file(page: Page, server: Server) -> None:
309    page.goto(server.PREFIX + "/input/fileupload.html")
310    input = page.locator("input[type=file]")
311
312    file_path = os.path.relpath(FILE_TO_UPLOAD, os.getcwd())
313    input.set_input_files(file_path)
314    assert (
315        page.evaluate("e => e.files[0].name", input.element_handle())
316        == "file-to-upload.txt"
317    )
318
319
320def test_locators_should_press(page: Page) -> None:
321    page.set_content("<input type='text' />")
322    page.locator("input").press("h")
323    page.eval_on_selector("input", "input => input.value") == "h"
324
325
326def test_locators_should_scroll_into_view(page: Page, server: Server) -> None:
327    page.goto(server.PREFIX + "/offscreenbuttons.html")
328    for i in range(11):
329        button = page.locator(f"#btn{i}")
330        before = button.evaluate(
331            "button => button.getBoundingClientRect().right - window.innerWidth"
332        )
333        assert before == 10 * i
334        button.scroll_into_view_if_needed()
335        after = button.evaluate(
336            "button => button.getBoundingClientRect().right - window.innerWidth"
337        )
338        assert after <= 0
339        page.evaluate("window.scrollTo(0, 0)")
340
341
342def test_locators_should_select_textarea(
343    page: Page, server: Server, browser_name: str
344) -> None:
345    page.goto(server.PREFIX + "/input/textarea.html")
346    textarea = page.locator("textarea")
347    textarea.evaluate("textarea => textarea.value = 'some value'")
348    textarea.select_text()
349    if browser_name == "firefox":
350        assert textarea.evaluate("el => el.selectionStart") == 0
351        assert textarea.evaluate("el => el.selectionEnd") == 10
352    else:
353        assert page.evaluate("window.getSelection().toString()") == "some value"
354
355
356def test_locators_should_type(page: Page) -> None:
357    page.set_content("<input type='text' />")
358    page.locator("input").type("hello")
359    page.eval_on_selector("input", "input => input.value") == "hello"
360
361
362def test_locators_should_screenshot(
363    page: Page, server: Server, assert_to_be_golden: Callable[[bytes, str], None]
364) -> None:
365    page.set_viewport_size(
366        {
367            "width": 500,
368            "height": 500,
369        }
370    )
371    page.goto(server.PREFIX + "/grid.html")
372    page.evaluate("window.scrollBy(50, 100)")
373    element = page.locator(".box:nth-of-type(3)")
374    assert_to_be_golden(element.screenshot(), "screenshot-element-bounding-box.png")
375
376
377def test_locators_should_return_bounding_box(page: Page, server: Server) -> None:
378    page.set_viewport_size(
379        {
380            "width": 500,
381            "height": 500,
382        }
383    )
384    page.goto(server.PREFIX + "/grid.html")
385    element = page.locator(".box:nth-of-type(13)")
386    box = element.bounding_box()
387    assert box == {
388        "x": 100,
389        "y": 50,
390        "width": 50,
391        "height": 50,
392    }
393
394
395def test_locators_should_respect_first_and_last(page: Page) -> None:
396    page.set_content(
397        """
398        <section>
399            <div><p>A</p></div>
400            <div><p>A</p><p>A</p></div>
401            <div><p>A</p><p>A</p><p>A</p></div>
402        </section>"""
403    )
404    assert page.locator("div >> p").count() == 6
405    assert page.locator("div").locator("p").count() == 6
406    assert page.locator("div").first.locator("p").count() == 1
407    assert page.locator("div").last.locator("p").count() == 3
408
409
410def test_locators_should_respect_nth(page: Page) -> None:
411    page.set_content(
412        """
413    <section>
414        <div><p>A</p></div>
415        <div><p>A</p><p>A</p></div>
416        <div><p>A</p><p>A</p><p>A</p></div>
417    </section>"""
418    )
419    assert page.locator("div >> p").nth(0).count() == 1
420    assert page.locator("div").nth(1).locator("p").count() == 2
421    assert page.locator("div").nth(2).locator("p").count() == 3
422
423
424def test_locators_should_throw_on_capture_without_nth(page: Page) -> None:
425    page.set_content(
426        """
427        <section><div><p>A</p></div></section>
428    """
429    )
430    with pytest.raises(Error, match="Can't query n-th element"):
431        page.locator("*css=div >> p").nth(1).click()
432
433
434def test_locators_should_throw_due_to_strictness(page: Page) -> None:
435    page.set_content(
436        """
437        <div>A</div><div>B</div>
438    """
439    )
440    with pytest.raises(Error, match="strict mode violation"):
441        page.locator("div").is_visible()
442
443
444def test_locators_should_throw_due_to_strictness_2(page: Page) -> None:
445    page.set_content(
446        """
447        <select><option>One</option><option>Two</option></select>
448    """
449    )
450    with pytest.raises(Error, match="strict mode violation"):
451        page.locator("option").evaluate("e => {}")
452
453
454def test_locators_set_checked(page: Page) -> None:
455    page.set_content("`<input id='checkbox' type='checkbox'></input>`")
456    locator = page.locator("input")
457    locator.set_checked(True)
458    assert page.evaluate("checkbox.checked")
459    locator.set_checked(False)
460    assert page.evaluate("checkbox.checked") is False
461
462
463def route_iframe(page: Page) -> None:
464    page.route(
465        "**/empty.html",
466        lambda route: route.fulfill(
467            body='<iframe src="iframe.html"></iframe>', content_type="text/html"
468        ),
469    )
470    page.route(
471        "**/iframe.html",
472        lambda route: route.fulfill(
473            body="""<html>
474          <div>
475            <button>Hello iframe</button>
476            <iframe src="iframe-2.html"></iframe>
477          </div>
478          <span>1</span>
479          <span>2</span>
480        </html>""",
481            content_type="text/html",
482        ),
483    )
484    page.route(
485        "**/iframe-2.html",
486        lambda route: route.fulfill(
487            body="<html><button>Hello nested iframe</button></html>",
488            content_type="text/html",
489        ),
490    )
491
492
493def test_locators_frame_should_work_with_iframe(page: Page, server: Server) -> None:
494    route_iframe(page)
495    page.goto(server.EMPTY_PAGE)
496    button = page.frame_locator("iframe").locator("button")
497    button.wait_for()
498    assert button.inner_text() == "Hello iframe"
499    button.click()
500    assert (
501        repr(page.frame_locator("iframe"))
502        == f"<FrameLocator frame=<Frame name= url='{server.PREFIX}/empty.html'> selector='iframe'>"
503    )
504
505
506def test_locators_frame_should_work_for_nested_iframe(
507    page: Page, server: Server
508) -> None:
509    route_iframe(page)
510    page.goto(server.EMPTY_PAGE)
511    button = page.frame_locator("iframe").frame_locator("iframe").locator("button")
512    button.wait_for()
513    assert button.inner_text() == "Hello nested iframe"
514    button.click()
515
516
517def test_locators_frame_should_work_with_locator_frame_locator(
518    page: Page, server: Server
519) -> None:
520    route_iframe(page)
521    page.goto(server.EMPTY_PAGE)
522    button = page.locator("body").frame_locator("iframe").locator("button")
523    button.wait_for()
524    assert button.inner_text() == "Hello iframe"
525    button.click()
526
527
528def route_ambiguous(page: Page) -> None:
529    page.route(
530        "**/empty.html",
531        lambda route: route.fulfill(
532            body="""
533        <iframe src="iframe-1.html"></iframe>
534        <iframe src="iframe-2.html"></iframe>
535        <iframe src="iframe-3.html"></iframe>
536    """,
537            content_type="text/html",
538        ),
539    )
540    page.route(
541        "**/iframe-*",
542        lambda route: route.fulfill(
543            body=f"<html><button>Hello from {urlparse(route.request.url).path[1:]}</button></html>",
544            content_type="text/html",
545        ),
546    )
547
548
549def test_locator_frame_locator_should_throw_on_ambiguity(
550    page: Page, server: Server
551) -> None:
552    route_ambiguous(page)
553    page.goto(server.EMPTY_PAGE)
554    button = page.locator("body").frame_locator("iframe").locator("button")
555    with pytest.raises(
556        Error,
557        match='.*strict mode violation: "body >> iframe" resolved to 3 elements.*',
558    ):
559        button.wait_for()
560
561
562def test_locator_frame_locator_should_not_throw_on_first_last_nth(
563    page: Page, server: Server
564) -> None:
565    route_ambiguous(page)
566    page.goto(server.EMPTY_PAGE)
567    button1 = page.locator("body").frame_locator("iframe").first.locator("button")
568    assert button1.text_content() == "Hello from iframe-1.html"
569    button2 = page.locator("body").frame_locator("iframe").nth(1).locator("button")
570    assert button2.text_content() == "Hello from iframe-2.html"
571    button3 = page.locator("body").frame_locator("iframe").last.locator("button")
572    assert button3.text_content() == "Hello from iframe-3.html"
573
574
575def test_drag_to(page: Page, server: Server) -> None:
576    page.goto(server.PREFIX + "/drag-n-drop.html")
577    page.locator("#source").drag_to(page.locator("#target"))
578    assert (
579        page.eval_on_selector(
580            "#target", "target => target.contains(document.querySelector('#source'))"
581        )
582        is True
583    )
584
585
586def test_locator_query_should_filter_by_text(page: Page, server: Server) -> None:
587    page.set_content("<div>Foobar</div><div>Bar</div>")
588    expect(page.locator("div", has_text="Foo")).to_have_text("Foobar")
589
590
591def test_locator_query_should_filter_by_text_2(page: Page, server: Server) -> None:
592    page.set_content("<div>foo <span>hello world</span> bar</div>")
593    expect(page.locator("div", has_text="hello world")).to_have_text(
594        "foo hello world bar"
595    )
596
597
598def test_locator_query_should_filter_by_regex(page: Page, server: Server) -> None:
599    page.set_content("<div>Foobar</div><div>Bar</div>")
600    expect(page.locator("div", has_text=re.compile(r"Foo.*"))).to_have_text("Foobar")
601
602
603def test_locator_query_should_filter_by_text_with_quotes(
604    page: Page, server: Server
605) -> None:
606    page.set_content('<div>Hello "world"</div><div>Hello world</div>')
607    expect(page.locator("div", has_text='Hello "world"')).to_have_text('Hello "world"')
608
609
610def test_locator_query_should_filter_by_regex_with_quotes(
611    page: Page, server: Server
612) -> None:
613    page.set_content('<div>Hello "world"</div><div>Hello world</div>')
614    expect(page.locator("div", has_text=re.compile('Hello "world"'))).to_have_text(
615        'Hello "world"'
616    )
617
618
619def test_locator_query_should_filter_by_regex_and_regexp_flags(
620    page: Page, server: Server
621) -> None:
622    page.set_content('<div>Hello "world"</div><div>Hello world</div>')
623    expect(
624        page.locator("div", has_text=re.compile('hElLo "world', re.IGNORECASE))
625    ).to_have_text('Hello "world"')
626
627
628def test_locator_should_return_page(page: Page, server: Server) -> None:
629    page.goto(server.PREFIX + "/frames/two-frames.html")
630    outer = page.locator("#outer")
631    assert outer.page == page
632
633    inner = outer.locator("#inner")
634    assert inner.page == page
635
636    in_frame = page.frames[1].locator("div")
637    assert in_frame.page == page
638
639
640def test_locator_should_support_has_locator(page: Page, server: Server) -> None:
641    page.set_content("<div><span>hello</span></div><div><span>world</span></div>")
642    expect(page.locator("div", has=page.locator("text=world"))).to_have_count(1)
643    assert (
644        page.locator("div", has=page.locator("text=world")).evaluate("e => e.outerHTML")
645        == "<div><span>world</span></div>"
646    )
647    expect(page.locator("div", has=page.locator('text="hello"'))).to_have_count(1)
648    assert (
649        page.locator("div", has=page.locator('text="hello"')).evaluate(
650            "e => e.outerHTML"
651        )
652        == "<div><span>hello</span></div>"
653    )
654    expect(page.locator("div", has=page.locator("xpath=./span"))).to_have_count(2)
655    expect(page.locator("div", has=page.locator("span"))).to_have_count(2)
656    expect(page.locator("div", has=page.locator("span", has_text="wor"))).to_have_count(
657        1
658    )
659    assert (
660        page.locator("div", has=page.locator("span", has_text="wor")).evaluate(
661            "e => e.outerHTML"
662        )
663        == "<div><span>world</span></div>"
664    )
665    expect(
666        page.locator(
667            "div",
668            has=page.locator("span"),
669            has_text="wor",
670        )
671    ).to_have_count(1)
672
673
674def test_locator_should_enforce_same_frame_for_has_locator(
675    page: Page, server: Server
676) -> None:
677    page.goto(server.PREFIX + "/frames/two-frames.html")
678    child = page.frames[1]
679    with pytest.raises(Error) as exc_info:
680        page.locator("div", has=child.locator("span"))
681    assert (
682        'Inner "has" locator must belong to the same frame.' in exc_info.value.message
683    )
684
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)