如何更正 Apify 中的选择器以从 JSON 数据 link 中获取数据?

How to correct the selector in Apify to get data from JSON data link?

我正在使用 Apify 从 json 文件链接中获取数据。这是 json 数据:

<html>
    <body>
        <pre>
            {"exhibitor-single":[{"firstname":"Ines","lastname":"Konwiarz","email":"georg.jansen@020epos.de"}]}
        </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 选择器。但是,它不返回任何数据。谁能帮我找出这里出了什么问题?提前致谢。

从 pageFunction 结构来看,我猜你正在使用 apify/web-scraper

如果您只想从 JSON 个链接获取数据,您可以轻松使用 apify/cheerio-scraper。它会花费更少的计算能力,因为您不需要打开整个浏览器。

您需要在 cheerio scraper 中使用设置 pageFunction 来获取 JSON 数据: 页面功能:

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 configurations 中的 Additional mime types 值为:

[
  "application/json"
]