如何通过Apify API与Node.js提取返回结果中的油价信息
提取Apify油价爬虫返回结果中的priceTag和gasType字段
你可以通过遍历返回的items数组,针对每个条目里的gasPrices数组使用map方法,筛选出仅包含priceTag和gasType的对象数组。以下是修正并添加提取逻辑后的完整代码:
import { ApifyClient } from 'apify-client'; // Initialize the ApifyClient with API token const client = new ApifyClient({ token: 'apify_api_********', }); // Prepare actor input const input = { "location": "Indiana", "maxCrawledPlacesPerSearch": 1 }; (async () => { // Run the actor and wait for it to finish const run = await client.actor("natasha.lekh/gas-prices-scraper").call(input); // Fetch and print actor results from the run's dataset (if any) console.log('Results from dataset'); const { items } = await client.dataset(run.defaultDatasetId).listItems(); items.forEach((item) => { // 检查当前条目是否包含有效gasPrices数组 if (item.gasPrices && Array.isArray(item.gasPrices)) { // 提取目标字段,生成新数组 const filteredGasPrices = item.gasPrices.map(gasItem => ({ gasType: gasItem.gasType, priceTag: gasItem.priceTag })); console.log('提取后的油价数据:', filteredGasPrices); } else { console.log('该条目无有效油价数据'); } }); })();
关键逻辑说明:
- 空值检查:先判断
item.gasPrices是否存在且为数组,避免因数据结构异常导致报错 - 字段提取:使用
Array.map()遍历gasPrices数组,每个元素仅保留gasType和priceTag两个字段,返回精简后的新数组 - 后续处理:你可以将
filteredGasPrices存入数据库、转换为JSON格式返回给前端,或者进行其他业务逻辑处理
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

