简体   繁体   English

如何使用 Puppeteer 将变量定义为抓取的元素

[英]How do I define a variable as a scraped element using Puppeteer

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null
    })
  const page = await browser.newPage()
  
  await page.goto('https://www.supremenewyork.com/shop/sweatshirts/ftq968f24/lhrblx1z5')
var productName = await page.evaluate(() => {
    document.querySelector('div[id="details"] > p[itemprop="model"]').innerText;
})

console.log(productName);

})()

When I run my code that is supposed to grab the name of the supreme item, it says undefined when it's supposed to log it in the console.当我运行应该获取至尊项目名称的代码时,它应该在控制台中记录它时显示未定义。

You are neither returning anything from the page.evaluate nor are you setting the value of productName .您既没有从page.evaluate返回任何内容,也没有设置productName的值。 Try something like this instead that uses $eval to return the innerText of the matching element:尝试这样的事情,而不是使用$eval返回匹配元素的innerText

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
  });
  const page = await browser.newPage();

  await page.goto(
    "https://www.supremenewyork.com/shop/sweatshirts/ftq968f24/lhrblx1z5"
  );

  const productName = await page.$eval(
    'div[id="details"] > p[itemprop="model"]',
    (el) => el.innerText
  );

  console.log(productName);
})();

If you prefer to use evaluate it would look like:如果您更喜欢使用evaluate ,它看起来像:

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
  });
  const page = await browser.newPage();

  await page.goto(
    "https://www.supremenewyork.com/shop/sweatshirts/ftq968f24/lhrblx1z5"
  );

  const productName = await page.evaluate(() => {
    // notice the return
    return document.querySelector('div[id="details"] > p[itemprop="model"]').innerText;
  });

  console.log(productName);
})();

If innerText doesn't return anything you may instead need to use something like textContent .如果innerText没有返回任何内容,您可能需要使用类似textContent的内容。

Hopefully that helps!希望这会有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM