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

求助:使用BeautifulSoup与Requests爬取TripAdvisor餐厅评论的问题

嘿,我来帮你搞定TripAdvisor爬取时遇到的这两个问题!

问题1:无法获取完整长度的评论内容

TripAdvisor对长评论默认会折叠显示,只展示部分内容并带有“Read more”按钮,但其实很多时候完整评论已经存在于页面源码中,只是被CSS隐藏了。你可以按以下思路处理:

  • 优先查找带有full_text类的span元素,这通常是隐藏的完整评论内容
  • 如果找不到full_text,再退而求其次提取partial_entry类的部分内容;如果必须要完整内容,可以检查页面是否通过AJAX加载完整评论,抓包找到对应的API接口后用requests直接请求

示例代码片段:

from bs4 import BeautifulSoup
import requests

# 替换为目标餐厅的评论页URL
target_url = "https://www.tripadvisor.com/..."
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"}

response = requests.get(target_url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")

for review in soup.find_all("div", class_="review-container"):
    # 尝试提取完整评论
    full_content = review.find("span", class_="full_text")
    if full_content:
        print("完整评论:", full_content.get_text(strip=True))
    else:
        # 提取折叠的部分评论
        partial_content = review.find("p", class_="partial_entry")
        print("部分评论:", partial_content.get_text(strip=True))
问题2:区分用户评论与商家回复

TripAdvisor的商家回复通常有专属的容器类标识,你可以通过这些标识精准过滤:

  • 用户评论一般包裹在review-content类的容器中
  • 商家回复则会被放在ownerResponse或response-container类的容器里,通常是对应评论的子元素

示例代码片段:

for review in soup.find_all("div", class_="review-container"):
    # 提取用户评论内容(自动排除商家回复)
    user_review_section = review.find("div", class_="review-content")
    if user_review_section:
        review_title = user_review_section.find("span", class_="noQuotes").get_text(strip=True)
        review_date = user_review_section.find("span", class_="ratingDate").get_text(strip=True)
        # 结合上面的方法提取完整评论内容
        print(f"标题:{review_title} | 日期:{review_date}")
    
    # 如需单独获取商家回复,可单独提取
    owner_reply = review.find("div", class_="ownerResponse")
    if owner_reply:
        reply_text = owner_reply.find("p").get_text(strip=True)
        print("商家回复:", reply_text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:38:54