when I use the document.querySelector in Chrome console, I obtain something, however when I use the same query with puppeeter. I get "undefined" or "Promise { }".
const text = await page.evaluate(() => document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)'));
console.log(text)
Thanks
That is because querySelector returns a node. Try to return innerText
,
const text = await page.evaluate(() => document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)').innerText);
console.log(text)
As far as I can tell, the reason you're not able to get your text back and output to your console is happening for two reasons:
evaluate
method.If you do something like the following, this should resolve your problem:
const text = await page.evaluate(() => {
const uiElement = document.querySelector('div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)'));
return uiElement.textContent;
});
console.log(text);
An alternative to the above function is to use puppeteers $eval
method as follows:
const elementSelector = 'div.tagCloud-slotAble.space--mv-2 > button:nth-child(1)';
const text = await page.$eval(elementSelector, (uiElement) => {
return uiElement.textContent;
});
console.log(text);
I personally prefer the second option (using $eval
) but it's a matter of preference. Both do the same thing.
It should be noted that anything you run in an evaluate
or $eval
method is executed in your page context ie. it is executed in the web page which is currently open in the remote browser. You can basically use this method to inject new UI elements into your web page during a test, execute JavaScript code inside your web page etc.
Or you can use it, as you are now, to find a UI element and return the text content from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With