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?
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"