Will
Will

Reputation: 131

How to properly pass a string to page.evaluate()?

Hi I am working on a web scraping script, and I have a function that currently returns to me a string. I want to pass the result of that function into page.evaluate. It is returning undefined - which according to the docs I think is for a good reason (non-serializable).

How would I go about this function?

    let imgTag = await comparer(img1, productImageURLarr); ///returns String

    let divSel = imgTag

    let parentdivs = await page.evaluate(
        (divSel) => {[...document.querySelectorAll(`img[alt=${divSel}]`)].map(elem => elem.closest('href'))
        }, divSel);

    console.log(parentdivs) ///returns undefined

also noted - when I put in the value of the string (not surrounded by quotes) instead of the expression it returns the object I want.

Upvotes: 1

Views: 312

Answers (1)

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8662

You have missed the return keyword in the parentdivs function.

    let parentdivs = await page.evaluate(divSel => {
      return [...document.querySelectorAll(`img[alt=${divSel}]`)].map(elem => elem.closest('href'))
    }, divSel);

Upvotes: 1

Related Questions