调用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
相关产品推荐
相关产品推荐

