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

调用Swiggy餐厅URL时出现Type error的原因排查

问题排查:Swiggy餐厅URL请求出现Type Error
  • 错误根源:你请求的https://www.swiggy.com/restaurants/meghana-foods-5th-block-koramangala-bangalore-229是Swiggy的前端网页地址,服务器返回的是HTML内容,而非JSON格式数据。直接调用res.json()尝试将HTML解析为JSON,必然会抛出类型错误。

  • 验证方法:将res.json()替换为res.text(),打印返回内容即可确认是完整的HTML页面:

async function getRequest() {
    fetch('https://www.swiggy.com/restaurants/meghana-foods-5th-block-koramangala-bangalore-229')
    .then( res => res.text())
    .then( data => console.log(data))
    .catch( e => console.log(e))
}
getRequest();
  • 解决方案:若要获取餐厅结构化数据,可通过页面内嵌的脚本内容提取:
async function getRestaurantData() {
    fetch('https://www.swiggy.com/restaurants/meghana-foods-5th-block-koramangala-bangalore-229')
    .then(res => res.text())
    .then(html => {
        // 提取页面内的JSON-LD结构化数据
        const jsonLdMatch = html.match(/<script type="application\/ld\+json">(.*?)<\/script>/s);
        if (jsonLdMatch) {
            const restaurantData = JSON.parse(jsonLdMatch[1]);
            console.log(restaurantData);
        }
        // 提取页面初始化状态数据(若存在)
        const initialStateMatch = html.match(/window\.__INITIAL_STATE__ = (.*?);/s);
        if (initialStateMatch) {
            const initialState = JSON.parse(initialStateMatch[1]);
            console.log(initialState);
        }
    })
    .catch(e => console.log(e));
}
getRestaurantData();

注意:Swiggy未公开官方API,直接抓取页面数据请确保遵守其服务条款。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:02:23