0

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()
Robert
  • 7,394
  • 40
  • 45
  • 64

1 Answers1

0

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.

Josh Heaps
  • 296
  • 2
  • 13