You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript循环遍历URL提取价格等数据并存储为本地JSON文件的实现问题

完整实现代码(Chrome控制台直接运行)

运行前提:先打开目标站点任意页面(如https://www.fahorro.com/首页),按F12打开开发者工具,切换到「控制台」标签,粘贴以下代码运行即可。

const urls = [
    'https://www.fahorro.com/3-a-ofteno-1-mg-oft-5-ml-gotas.html',
    'https://www.fahorro.com/zamoprax-0-25-mg-c2-con-30-tabletas.html'
];
// 存储最终结果的数组
const result = [];
// DOM解析器,用于把接口返回的HTML文本转成可查询的DOM对象
const parser = new DOMParser();

// 用async/await处理异步,保证执行顺序可控
(async function() {
    for (const url of urls) {
        try {
            const response = await fetch(url);
            const html = await response.text();
            const doc = parser.parseFromString(html, 'text/html');
            // 提取对应字段,加可选链防止节点不存在时报错
            const price = doc.querySelector('span.price')?.textContent?.trim() || '未获取到价格';
            const sku = doc.querySelector('td[data-th="SKU"]')?.textContent?.trim() || '未获取到SKU';
            // 按要求的结构推入结果数组
            result.push({
                link: url,
                prices: price,
                sku: sku
            });
            console.log(`已完成爬取:${url}`);
        } catch (err) {
            console.error(`爬取失败:${url},错误信息:`, err);
            result.push({
                link: url,
                prices: '爬取失败',
                sku: '爬取失败'
            });
        }
        // 若需要降低请求频率可取消下面的注释,1000代表每次请求间隔1秒,可自行调整数值
        // await new Promise(resolve => setTimeout(resolve, 1000))
    }
    // 所有URL爬取完成后导出JSON文件
    const jsonStr = JSON.stringify(result, null, 2);
    const blob = new Blob([jsonStr], {type: 'application/json'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = '商品价格数据.json';
    a.click();
    URL.revokeObjectURL(downloadUrl);
})();
注意事项
  • 不要在其他域名下的页面控制台运行这段代码,会触发浏览器跨域限制,必须先打开fahorro.com的任意页面再运行
  • 代码加了兜底逻辑,就算部分页面节点不存在也不会中断整个爬取流程

内容的提问来源于stack exchange,提问作者Robert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:36:05