1

I use the Puppeteer framework to automize tests. I need to find an element as per a text:

await page.focus(//span[contains(text(), 'Name')]])

<span class="some_placeholder">Name</span>
<span class="some_placeholder">Phone Number</span>

But in this case the following error occurs:

Evaluation failed: DOMException: Failed to execute 'querySelector' on Document '' is not a valid selector..

span[class='name'] finds some elements successfully but only one element is needed.

focus() accepts a CSS selector and does not accept contains() or text() methods.

How should I code the search condition correctly?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
A user
  • 29
  • 1
  • 9
  • Does this answer your question? [How to click on element with text in Puppeteer](https://stackoverflow.com/questions/47407791/how-to-click-on-element-with-text-in-puppeteer). It's virtually the same as far as the selection process goes if you allow for calling the similar method `.click()` rather than `.focus()`, and the dupe suggestion is the canonical thread for this. – ggorlen Dec 30 '21 at 03:43

1 Answers1

4

You caan use XPath with page.$x() and then call elementHandle.focus():

const [element] = await page.$x('//span[contains(text(), "Name")]');
await element.focus();
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26