Reputation: 3093
I'm trying to work out how to efficiently grab an element from a page that contains a specific string.
The element is in an <a>
tag however it's classes/ids are randomly generated.
The only way I can achieve this is by looping over every <a>
tag and checking if the textContent matches.
<a>Match this text foo</a>
I've also tried using the xPath expression however I can figure out how to use the returned elements.
//a[contains(text(),'Match this text')]
Anyone have a better solution?
Upvotes: 2
Views: 5485
Reputation: 8672
The page.$x(expression)
method returns: <Promise<Array<ElementHandle>>>
. So you can get specific element by index or just with the destructuring assignment.
For instance:
const links = await page.$x('//a[text()="Specific Text"]'); // returns: <Promise<Array<ElementHandle>>>
await links[0].click();
or even better with the destructuring assignment:
const [ link ] = await page.$x('//a[text()="Specific Text"]');
await link.click();
Upvotes: 3