How to parameterize element locators in pytest playwright

421 views Asked by At

How to write an element locator of which the text value could be parameterized in Pytest Playwright.

Eg: We can do it like this in Selenium,

  • initially define a string: String product_code = form[@data-id='PRODUCT_CODE']
  • and then updating the variable value by: By.xpath(lbl.replace("PRODUCT_CODE", product)

How can we achieve the same in pytest playwright for an element locator with get_by_text?

I have tried the following and didn't work.

test_fav_list = page.query_selector(f'[name="{self.element_name}"]')
element_name = name
test_fav_list.click()
element = self.page.query_selector(f'[name="{name}"]')
if element:
    element.click()
1

There are 1 answers

0
Josh Heaps On

Query selector returns an element handle, which is outdated and discouraged by the playright documentation. I recommend following the documentation's advice and switch to using locators.

Using your code, it might look something like this:

test_fav_list = page.locator(f'[name="{self.element_name}"]').click()
self.page.locator(f'[name="{name}"]').click()

This should fix your issue.