Apify Puppeteer Scraper不會在背景關系物件中公開 jquery 。我需要訪問 Puppeteer Scraper pageFunction 中的外部 JSON 資料源,然后遍歷其中一個節點。如果 jquery 可用,我會這樣做:
$.get(urlAPI, function(data) {
$.each(data.feed.entry, function(index, value) {
var url = value.URL;
uj5u.com熱心網友回復:
由于 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,
}
}
uj5u.com熱心網友回復:
您不需要 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521615.html
標籤:傀儡师应用
