【问题标题】:Can't Scrape Input Value from dolartoday.com with Puppeteer无法使用 Puppeteer 从 dolartoday.com 抓取输入值
【发布时间】:2019-03-03 09:31:50
【问题描述】:

我想用以下方法刮取元素#result 的value:

 const puppeteer = require('puppeteer');

    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.goto('https://dolartoday.com');
      await console.log(page.evaluate(() => document.getElementById('result')));

      await browser.close();
    })();

但它仍然会记录以下错误:

(node:74908) UnhandledPromiseRejectionWarning: Error: Navigation Timeout Exceeded: 30000ms exceeded
at Promise.then (/Volumes/DATOS/Dropbox/workspaces/dolar-today/server/node_modules/puppeteer/lib/NavigatorWatcher.js:71:21)
at <anonymous>
(node:74908) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:74908) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

关于如何解决这个问题的任何想法?

【问题讨论】:

  • Navigation Timeout Exceeded: 30000ms exceeded

标签: javascript node.js web-scraping puppeteer


【解决方案1】:

首先,您尝试在console.log()(同步函数)上使用await 运算符,而不是在page.evaluate()(异步函数)上。

您还尝试将 Page DOM 元素返回到 Node.js 环境,这将不起作用,因为 page.evaluate() 期待 serializable 返回值。

如果你想返回网页上#result元素的value,你应该重写你的逻辑如下:

console.log(await page.evaluate(() => document.getElementById('result').value));

此外,导航时间已超过 30000 毫秒(默认最大值)。您可以使用 page.goto() 函数中的 timeout 选项扩展最长导航时间:

await page.goto('https://dolartoday.com', {
  timeout: 60000,
});

您还可以使用page.setRequestInterception() 和page.on('request') 拒绝在网页中加载不必要的资源。这将使您的网页加载速度更快:

await page.setRequestInterception(true);

page.on('request', request => {
  if (['image', 'stylesheet', 'font'].indexOf(request.resourceType()) !== -1) {
    request.abort();
  } else {
    request.continue();
  }
});

您的最终程序应如下所示:

'use strict';

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.setRequestInterception(true);

  page.on('request', request => {
    if (['image', 'stylesheet', 'font'].indexOf(request.resourceType()) !== -1) {
      request.abort();
    } else {
      request.continue();
    }
  });

  await page.goto('https://dolartoday.com', {
    timeout: 60000,
  });

  console.log(await page.evaluate(() => document.getElementById('result').value));

  await browser.close();
})();

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多