1

As you can see, I added puppeteer and I am always getting the error. I am trying to use the getElementById function to manipulate my html front-end.

const puppeteer = require('puppeteer');

(async function getPrice(){

let URL= 'https://www.coingecko.com/en/coins/synthetix-network-token';
let browser = await puppeteer.launch();
let page = await browser.newPage();
await page.goto(URL, {waitUntil: 'networkidle2'});

let data = await page.evaluate(() => {

    try {
    let price=document.querySelector('div[class="text-3xl"] > span').innerText;

        return {
           price
        }
    
    }catch(err) {
    reject(err.toString());
    }})


console.log(Object.values(data));
document.getElementById("snxprice").innerHTML = Object.values(data);
await browser.close();


}().catch(function(error) {
    console.error('Document is not defined!');
    process.exit();
});
rani
  • 11
  • 4
  • Try to explain better the question, is a good thing to add a link to puppeteer, not all know what is ... next, describe if you compile using babel or if you are in nodejs, in few words, define context, this can help to answer your questions. Please avoid post like "solve this problem..." and post the code. The last thing try to format your code better. Hope this help you. – LXG Sep 07 '20 at 18:55
  • The formatting of the code makes it hard to tell what's inside `evaluate` and what is in Node. If it's outside `evaluate`, `document` is undefined. – ggorlen Feb 25 '23 at 02:18

1 Answers1

1

This line: document.getElementById("snxprice").innerHTML = Object.values(data); is not valid in puppeteer.

You have to use page.evaluate every time when you need the DOM document (you need to evaluate the page context), something like this:

await page.evaluate(data => {
    const element = document.querySelector('#snxprice')
    element.innerHTML = Object.values(data)
 }, data)

Note: #snxprice is most probably inside an iframe as puppeteer is unable to find it in the page. So what you will need in the end is frame.evaluate.

theDavidBarton
  • 7,643
  • 4
  • 24
  • 51
  • Thank you David for your answer. I am not getting errors anymore. I added also to the lines you wrote: document.addEventListener("DOMContentLoaded", function(event) {. However, I am unable to update the values in the html file, querySelector and getElementById are not working properly, would you have any idea why? – rani Sep 08 '20 at 08:55
  • If your element has `value` property you could set it like this: ```await page.evaluate(data => { document.querySelector('#snxprice').value = Object.values(data) }, data)``` https://github.com/puppeteer/puppeteer/issues/441 https://stackoverflow.com/questions/47966510/how-to-fill-an-input-field-using-puppeteer – theDavidBarton Sep 08 '20 at 09:08
  • No, element does not have value property. My javascript is working fine, however what I am having difficulties with is sending that value to the specific id on html. – rani Sep 08 '20 at 09:45