Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puppeteer: document.querySelector works on console but not on pupppeteer

Tags:

puppeteer

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

like image 234
Gryz Avatar asked Sep 15 '18 11:09

Gryz


2 Answers

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)
like image 115
Md. Abu Taher Avatar answered Oct 20 '22 00:10

Md. Abu Taher


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:

  • You're not returning the value from your evaluate method.
  • You're retrieving the element but not the text content from the element.

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.

like image 36
AJC24 Avatar answered Oct 19 '22 23:10

AJC24