2

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?

atoms
  • 2,993
  • 2
  • 22
  • 43
  • Don't you have some parent element you can ID? so you can do something like `.parent-div-class A` – hardkoded Aug 14 '19 at 13:41
  • Unfortunately not. The site has gone to great lengths to make all selectors dynamic and the HTML is very basic. I'm sure the xPath should be more efficient however I can't figure out how to use the `ElementHandle` thats returned. – atoms Aug 14 '19 at 13:43

1 Answers1

3

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();
Yevhen Laichenkov
  • 7,746
  • 2
  • 27
  • 33
  • perfect thank you! I didn't realise the ElementHandle can be used in this manner. – atoms Aug 14 '19 at 13:58
  • Do you know how I would read the URL of the tag from the `ElementHandle` object? Im using `c#` for this – atoms Aug 14 '19 at 20:43
  • 1
    Hey @atoms. What do you mean by the URL of the tag from `ElementHandle` object? Could you please give an example? – Yevhen Laichenkov Aug 14 '19 at 22:00
  • 1
    I found it! Was to call `ElementHandle[0].getPropertyAsync("href")`. Obvious when you know how! Thanks for your help! – atoms Aug 15 '19 at 07:24