【发布时间】:2020-01-12 03:38:13
【问题描述】:
我在这个例子中使用puppeteer 1.19.0 和date.js 0.3.3
const puppeteer = require('puppeteer');
const date = require('date.js');
let scrape = async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.exposeFunction('formatDate', (text) =>
date(text));
await page.goto('https://www.daraz.com.bd/products/the-vip-suction-mobile-phone-stand-pocket-size-i113492895-s1030756115.html');
await page.waitFor(1000);
const result = await page.evaluate(() => {
let elements = document.querySelectorAll('#module_product_qna > div.pdp-mod-qna > div:nth-child(2) > ul > li')
for (var element of elements)
{
let question = element.querySelector('div:first-of-type > div.qna-content').innerText;
let qtime = element.querySelector('div:first-of-type > div.qna-meta').innerText;
let q = qtime.match(/- (.+)/);
qtime = formatDate(q[1]);
return {
question,
qtime
}
}});
browser.close();
return result;
};
scrape().then((value) => {
console.log(value);
});
您可以看到我正在尝试使用 date.js 库的日期函数通过 puppeteer exposeFunction 解析相对日期,但日期函数在页面上下文中不起作用。有什么建议我做错了吗?
感谢您的回复!
【问题讨论】:
-
“它不起作用”是什么意思?
-
我的意思是日期函数在页面上下文之外工作正常。但它在页面评估功能内不起作用。
-
需要在自己抓取的页面中导入库
-
@Rashomon 你能详细说明一下吗?自己的页面是什么意思?
-
对不起,没有意识到你已经使用了
exposeFunction。您可以尝试使用window.formatDate访问formatDate吗?
标签: javascript node.js web-scraping puppeteer