Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use locator in evaluate's javascript in Playwright python

I have the following script running:

def test_combobox_selected_by_label(page):
    page.goto("http://www.tizag.com/htmlT/htmlselect.php")
    element = page.get_by_role("combobox")
    element.select_option("Colorado -- CO")
    selected_label = page_custom.evaluate("document.getElementsByName('selectionField')[0].options[document.getElementsByName('selectionField')[0].selectedIndex].text")
    assert selected_label == "Colorado -- CO"

I"m using javascript for element, to extract the selected option’s label text.

How could I reformat the element variable to use the previously defined locator (get_by_role("combobox")) from select_elem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In short, how can I use the locator variable (select_elem) in evaluate’s javascript?

Locators should be:

page.get_by_role("combobox")

or

page.locator("[name=selectionField]").first

Note: you may run the above script, this is a live page.

>Solution :

If I understand correctly, you’re looking for element.evaluate():

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("http://www.tizag.com/htmlT/htmlselect.php")
    element = page.get_by_role("combobox")
    element.select_option("Colorado -- CO")
    text = element.evaluate("el => el.options[el.selectedIndex].text")
    assert text == "Colorado -- CO"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading