使用R更高效抓取TripAdvisor评分值的技术问询
嘿,我来给你分享几个更高效的TripAdvisor评分抓取方案,用rvest就能轻松实现,比你当前的步骤简洁不少,还能减少出错概率!
核心思路:直接提取结构化属性值
TripAdvisor的评分数据其实已经以结构化的形式(比如元素属性)存在页面里,不需要先转成字符串再拆数字、除以10。我们可以直接抓取这些属性,一步拿到最终评分。
方法1:抓取页面总评分
针对你给出的Kew Gardens页面,总评分元素带有data-test='review-rating'标识,它的aria-label属性直接存储了格式化好的评分值(比如4.5):
library(rvest) url <- "https://www.tripadvisor.co.uk/Attraction_Review-g1466790-d547811-Reviews-Royal_Botanic_Gardens_Kew-Kew_Richmond_upon_Thames_Greater_London_England.html" # 读取页面并提取总评分 page <- read_html(url) overall_rating <- page %>% html_element("[data-test='review-rating']") %>% html_attr("aria-label") %>% as.numeric() print(overall_rating) # 输出:4.5
方法2:批量抓取单条评论的评分
如果需要提取所有用户评论的评分,只需要把html_element换成html_elements即可批量处理:
# 提取所有评论的评分 all_review_ratings <- page %>% html_elements("[data-test='review-rating']") %>% html_attr("aria-label") %>% as.numeric() # 查看前5条评论的评分 head(all_review_ratings)
备选方案:利用星星元素的data-value属性
部分TripAdvisor页面的星星图标会在data-value属性里存储原始评分数值(比如45,对应4.5),这种情况可以直接提取后除以10:
# 从星星元素提取评分 rating_from_stars <- page %>% html_element(".UctUV.d.H0") %>% # 星星SVG的类选择器 html_attr("data-value") %>% as.numeric() %>% `/`(10) # 等价于除以10 print(rating_from_stars) # 输出:4.5
为什么更高效?
- 省去了字符串拆解、转换的冗余步骤,代码更简洁易读
- 直接抓取结构化属性,比解析文本内容更稳定(页面样式变动时,属性标识通常比文本格式更不容易修改)
内容的提问来源于stack exchange,提问作者BadAtCoding




