使用 Apify Puppeteer Scraper 访问和循环外部数据源
Access and Loop External Datasource with Apify Puppeteer Scraper
Apify Puppeteer Scraper does not expose jquery in the context object。我需要访问 Puppeteer Scraper pageFunction 中的外部 JSON 数据源,然后遍历其中一个节点。如果 jquery 可用,我会这样做:
$.get(urlAPI, function(data) {
$.each(data.feed.entry, function(index, value) {
var url = value.URL;
由于handlePageFunction运行在node 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 or Apify's own httpRequest 等通用库从独立参与者中提取外部数据。不幸的是,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
}
Apify Puppeteer Scraper does not expose jquery in the context object。我需要访问 Puppeteer Scraper pageFunction 中的外部 JSON 数据源,然后遍历其中一个节点。如果 jquery 可用,我会这样做:
$.get(urlAPI, function(data) {
$.each(data.feed.entry, function(index, value) {
var url = value.URL;
由于handlePageFunction运行在node 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 or Apify's own httpRequest 等通用库从独立参与者中提取外部数据。不幸的是,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
}