【发布时间】:2019-07-05 23:00:47
【问题描述】:
我正在尝试使用 Puppeteer 进行一些网络抓取,我需要将值检索到我正在构建的网站中。
我尝试将 Puppeteer 文件加载到 html 文件中,就像它是 JavaScript 文件一样,但我一直收到错误消息。但是,如果我在 cmd 窗口中运行它,它运行良好。
Scraper.js:getPrice();
function getPrice() {
const puppeteer = require('puppeteer');
void (async () => {
try {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('http://example.com')
await page.setViewport({ width: 1920, height: 938 })
await page.waitForSelector('.m-hotel-info > .l-container > .l-header-section > .l-m-col-2 > .m-button')
await page.click('.m-hotel-info > .l-container > .l-header-section > .l-m-col-2 > .m-button')
await page.waitForSelector('.modal-content')
await page.click('.tile-hsearch-hws > .m-search-tabs > #edit-search-panel > .l-em-reset > .m-field-wrap > .l-xs-col-4 > .analytics-click')
await page.waitForNavigation();
await page.waitForSelector('.tile-search-filter > .l-display-none')
const innerText = await page.evaluate(() => document.querySelector('.tile-search-filter > .l-display-none').innerText);
console.log(innerText)
} catch (error) {
console.log(error)
}
})()
}
索引.html:
<html>
<head></head>
<body>
<script src="../js/scraper.js" type="text/javascript"></script>
</body>
</html>
预期的结果应该是 Chrome 控制台中的这个:
但我收到了这个错误:
我做错了什么?
【问题讨论】:
-
puppeteer 是一个无头浏览器,你不能在网络浏览器中加载它。对于可以在浏览器中运行的其他包,请查看:stackoverflow.com/questions/19059580/…
-
您可以将 Puppeteer 命令转换为相应的浏览器 API,但有些可能不起作用。
waitForNavigation- 你希望它如何工作?您导航到另一个页面。会有另一个页面不知道这个脚本。之所以存在 Puppeteer 这样的 Node 包,是因为有些事情单靠浏览器是无法实现的。 -
谢谢你们!我已经尝试过 Browserify,但我一直收到此错误:i.imgur.com/LfWOlyv.png 我猜 puppeteer 不适用于 Browserify?我使用 waitForNavigation 是因为我需要获取单击按钮后出现的值,因此我必须使用它,否则我将无法获取该值,因为它不会等到站点完全自行加载。我需要的只是将常量 innerText 的值发送到 JavaScript,这样我就可以在我用 HTML、CSS 和 JS 构建的网站中使用它,但我不知道如何实现。跨度>
标签: javascript node.js web-scraping puppeteer