I am trying to store a variable of list items from a dropdown on my company's web app. I am writing an automation test that will randomly click on one of the 40 possible list items in this drop down. Is this something that is possible with Playwright? This, among other variations of this, is what I have attempted but I always get TypeError: object of type 'Locator' has no len() . I'm assuming this is because my list_item variable has no elements in it? Any help would be greatly appreciated here. Thank you.
def test_hazard_action_from_homepage(page_setup):
# Set page variable to conftest.py page_setup fixture
page = page_setup
# Click button:has-text("Hazard Action")
page.locator("button:has-text(\"Hazard Action\")").click()
# Click input[name="hazard_date"]
page.locator("input[name=\"hazard_date\"]").click()
# Click #hazard_date_root >> text=Today
page.locator("#hazard_date_root >> text=Today").click()
# Click '//span[@aria-labelledby="select2-hazard_site-container"]'
page.locator('//span[@aria-labelledby="select2-hazard_site-container"]').click()
# Create list of "li" then randomly click
list_item = page.locator('//ul[contains(@class, "select2-results__option")] > li')
page.click(random.choice(list_item))
Playwright handle differently with elements than the older python browsers...
in dropdown you should page.select_option(selector)
that's also why in Playwright you can't click a check box, you should page.check(selector) https://playwright.dev/python/docs/api/class-page#page-select-option
For anyone interested. I resolved this using the html-to-json plugin. I used the following function to get the number of list items.
def li_count(page, ul):
lis = page.locator(ul).inner_html()
lis_json = len(html_to_json.convert(lis)["li"])
li_num = randrange(0, lis_json)
return li_num
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.