Apify Puppeteer Scraper不会在上下文对象中公开 jquery 。我需要访问 Puppeteer Scraper pageFunction 中的外部 JSON 数据源,然后遍历其中一个节点。如果 jquery 可用,我会这样做:
$.get(urlAPI, function(data) {
$.each(data.feed.entry, function(index, value) {
var url = value.URL;
Apify Puppeteer Scraper不会在上下文对象中公开 jquery 。我需要访问 Puppeteer Scraper pageFunction 中的外部 JSON 数据源,然后遍历其中一个节点。如果 jquery 可用,我会这样做:
$.get(urlAPI, function(data) {
$.each(data.feed.entry, function(index, value) {
var url = value.URL;
由于 handlePageFunction 在节点 js 上下文中运行,因此没有 jQuery。您可以使用 Apify SDK 轻松地将 jQuery 包含到 page.evaluate 函数中。
async function pageFunction(context) {
const { page, request, log, Apify } = context;
await Apify.utils.puppeteer.injectJQuery(page);
const title = await page.evaluate(() => {
// There is jQuery include as we incleded it using injectJQuery method
return $('title').text()
});
return {
title,
}
}
编辑:使用requestAsBrowser。
async function pageFunction(context) {
const { page, request, log, Apify } = context;
const response = await Apify.utils.requestAsBrowser({ url: "http://example.com" });
const data = JSON.parse(response.body);
return {
data,
}
}
您不需要 JQuery(如果您熟悉它,则可以)来访问外部资源。
通常,我们通过诸如request或 Apify 自己的httpRequest等通用库从独立的 Actor 中提取外部数据。不幸的是,Puppeteer Scraper 不允许使用库(只能动态下载,这可能是矫枉过正)。
我只会使用现代的fetch浏览器调用。它比 JQuery 的 AJAX 更好,并且不需要注入。
async function pageFunction(context) {
const { page, request, log, Apify } = context;
const json = await page.evaluate(() => {
// There is jQuery include as we incleded it using injectJQuery method
return await fetch('http://my-json-url.com').then((resp) => resp.json())
});
// Process the JSON
}