我正在使用 Apify 從 json 檔案鏈接中獲取資料。這是json資料:
<html>
<body>
<pre>
{"exhibitor-single":[{"firstname":"Ines","lastname":"Konwiarz","email":"[email protected]"}]}
</pre>
</body>
</html>
所以,我在 apify webscraper 任務中使用了以下代碼。
async function pageFunction(context) {
const request = context.request;
const $ = context.jQuery;
var data = $('body > pre').html();
var items = JSON.parse(data);
return {
Url: request.url,
Last_Name: items[`exhibitor-single`].lastname,
First_Name: items[`exhibitor-single`].firstname,
Email: items[`exhibitor-single`].email
};
}
該變數data具有適用于 json 資料的正確 css 選擇器。但是,它沒有回傳任何資料。誰能幫我找出這里出了什么問題?提前致謝。
uj5u.com熱心網友回復:
從 pageFunction 結構來看,我猜你正在使用apify/web-scraper。
如果您只想從 JSON 鏈接中獲取資料,您可以輕松使用apify/cheerio-scraper。由于您不需要打開整個瀏覽器,因此它將花費更少的計算能力。
您需要在cheerio scraper 中使用設定pageFunction 來獲取JSON 資料:pageFunction:
async function pageFunction(context) {
const { request ,json } = context;
const items = json;
return {
Url: request.url,
Last_Name: items.lastname,
First_Name: items[`exhibitor-single`].firstname,
Email: items.email
};
}
Cheerio scraper 默認只支持 HTML 回應,您需要在 Advanced 配置中更新 Additional mime types 的值:
[
"application/json"
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521616.html
