【发布时间】:2020-05-27 03:52:37
【问题描述】:
我写了这段代码,但我无法获取链接:
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const countries = ['us', 'gb', 'ca', 'au', 'de', 'nz', 'albania', 'nl', 'is'];
const pia = 'https://www.privateinternetaccess.com/pages/network/'
await page.goto(pia);
for (let i = 0; i < countries.length; i++) {
let el = document.querySelectorAll(`#${countries[i]} > div > div > div.modal-body > div > .subregion > center > .hostname`);
for (let j = 0; j < el.length; j++) {
let url = `htpp://${el[j].innerText}:8888/speedtest`;
console.log(url);
}
}
await browser.close();
})();
问题是,当我在浏览器的控制台中粘贴“国家 [...]”和 for 循环时,它工作得很好,但是当我从 Node 尝试它时,它给了我这个大错误,即使它打印如果我使用“await page.content()”函数,则整个页面:
(node:16300) UnhandledPromiseRejectionWarning: ReferenceError: document is not defined
at C:\Users\jason\Desktop\pptr\script.js:15:17
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:16300) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:16300) [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.
我认为这可能是我定位元素的方式,但它再次在浏览器的控制台中运行良好。我错过了什么?欢迎所有帮助!谢谢!
【问题讨论】:
-
document在 Node.JS 的上下文中不存在。如果要在浏览器上执行代码,需要使用evaluate函数。 -
谢谢!我还在学习它。
标签: javascript puppeteer innerhtml