如何通过新版Google Places API获取5条以上的评论?
问题:新版Google Places API如何获取5条以上评论,分页功能是否真实存在?
我尚未找到针对以下问题的现代化解决方案:如何通过新版Google Places API从商家页面获取5条以上的评论。我咨询过一些AI,它们提到存在分页功能,但我无法实现该功能。请问分页功能是否真实存在?
我正在开发一个项目,例如从知名雕像的页面获取评论,使用HTML、CSS和原生JavaScript(Node.js、Express)进行开发,但始终未能找到有效解决方案,每次仅能获取并渲染5条评论。以下是我的代码:
app.get('/api/google-reviews', async (req, res) => { const GOOGLE_PLACE_ID = 'PLACE_ID'; const API_KEY = 'KEY'; const pageToken = req.query.pageToken || ''; const url = `https://maps.googleapis.com/maps/api/place/details/json?place_id=${GOOGLE_PLACE_ID}&fields=reviews,user_ratings_total&key=${API_KEY}&pagetoken=${pageToken}`; try { const response = await fetch(url); const data = await response.json(); if (data.result) { const totalReviews = data.result.user_ratings_total || 0; const reviews = data.result.reviews || []; const nextPageToken = data.next_page_token || null; res.json({ reviews: reviews, totalReviews: totalReviews, nextPageToken: nextPageToken }); } else { res.status(404).json({ error: 'No reviews found' }); } } catch (error) { console.error('Error fetching reviews:', error); res.status(500).json({ error: 'Failed to fetch reviews' }); } });
解答
分页功能现状
新版Google Places API的Place Details端点已移除评论分页功能,当前该接口每次最多返回5条最新评论,不再支持pagetoken参数,也不会返回next_page_token字段。你咨询的AI信息可能基于旧版API,不符合当前的API规则。
代码问题分析
你代码中尝试使用的pagetoken参数在当前API版本中已被废弃,无论是否传递该参数,接口都会固定返回最多5条评论,因此无法通过分页获取更多内容。
可行替代方案
如果需要获取更多评论,目前有两种可选路径:
- Place Search端点补充:使用Place Search接口(如
textsearch或nearbysearch),结合不同的搜索条件(如调整搜索半径、关键词),可能获取到不同的评论样本,但无法保证覆盖全部评论。 - Google My Business API(限商家自身):若你拥有目标商家的管理权限,可通过该API获取更多评论,但需要额外的权限申请和身份认证,仅适用于商家自有账号的场景。
修正后的代码
既然分页已不可用,可简化代码移除无效的分页逻辑:
app.get('/api/google-reviews', async (req, res) => { const GOOGLE_PLACE_ID = 'PLACE_ID'; const API_KEY = 'KEY'; const url = `https://maps.googleapis.com/maps/api/place/details/json?place_id=${GOOGLE_PLACE_ID}&fields=reviews,user_ratings_total&key=${API_KEY}`; try { const response = await fetch(url); const data = await response.json(); if (data.result) { const totalReviews = data.result.user_ratings_total || 0; const reviews = data.result.reviews || []; res.json({ reviews: reviews, totalReviews: totalReviews }); } else { res.status(404).json({ error: 'No reviews found' }); } } catch (error) { console.error('Error fetching reviews:', error); res.status(500).json({ error: 'Failed to fetch reviews' }); } });
内容的提问来源于stack exchange,提问作者Heebo
相关产品推荐
相关产品推荐

