Is there any method (didn\'t find in API) or solution to click on element with text?
For example I have html:
The solution is
(await page.$$eval(selector, a => a
.filter(a => a.textContent === 'target text')
))[0].click()
There is no supported css selector syntax for text selector or a combinator option, my work around for this would be:
await page.$$eval('selector', selectorMatched => {
for(i in selectorMatched)
if(selectorMatched[i].textContent === 'text string'){
selectorMatched[i].click();
break;//Remove this line (break statement) if you want to click on all matched elements otherwise the first element only is clicked
}
});
made quick solution to be able to use advanced css selectors like ":contains(text)"
so using this library you can just
const select = require ('puppeteer-select');
const element = await select(page).getElement('button:contains(Button text)');
await element.click()
There are many answers suggesting contains
but I don't see any motivation for this imprecision given OP's use case which, by all appearances, is an exact match with a target string of "Button text"
and an element <button>Button text</button>
.
I'd prefer to use the more precise [text()="Button text"]
, which avoids a false positive when the button is, say, <button>Button text and more stuff</button>
:
const [el] = await page.$x('//*[@class="elements"]//a[text()="Button text"]');
el && (await el.click());
This anticipates the opposite scenario of this answer which attempts to be as permissive as possible.
Many answers also missed the .elements
parent class requirement.
Here is my solution:
let selector = 'a';
await page.$$eval(selector, anchors => {
anchors.map(anchor => {
if(anchor.textContent == 'target text') {
anchor.click();
return
}
})
});
I had to:
await this.page.$eval(this.menuSelector, elem => elem.click());