jeudi 19 novembre 2020

Set a variable dynamically in javascript

I'm doing some webscraping using puppeteer and node.js. I'm looping through data and I want to store the data dynamically to a variable depending on what I'm scraping during the loop. I'm then storing this data into a MySQL database.

Here is a sample of the code:

const subQ1
const subQ1A

const subQ2
const subQ2A

const subQ3
const subQ3A

for(var i = 1; i < 4; i++){
    
    | this is where the number of the loop should go (i), same thing below
    v
subQi = await page.evaluate((i) => {
            var linkGet = document.querySelector(`body > div.page-content.container > div:nth-child(${i}) > div.question_part_label`).innerHTML
         return linkGet;         
        },i);

subQ(i)A = await page.evaluate((i) => {
            var linkGet = document.querySelector(`body > div.page-content.container > div:nth-child(${i}) > div.question_part_label`).innerHTML
         return linkGet;         
        },i);
}

I know this might not be the practical way of doing things but I'm a bit of a noob. I've seen eval() as an option but everyone seems to suggest not using it and I'm wondering if theres another way of doing this. Thanks :)




Aucun commentaire:

Enregistrer un commentaire