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

如何使用Scrapy提取Trustpilot星级评分对应的类名?

能否通过.star-rating选择器提取count-2/count-3这类类名?

当然可以!不过直接用.css('.star-rating')(或者不同工具里的类似选择器)只是第一步——它帮你定位到目标元素,但要拿到count-*这类类名,还需要额外几步来提取元素的class属性内容。

下面按常见的爬虫/前端工具场景给你举例子:

1. jQuery 或浏览器原生DOM操作

如果是在浏览器控制台调试,或者用基于浏览器的爬虫工具,你可以这么做:

// 先定位到星级元素
const starEl = $('.star-rating');
// 获取元素的所有类名字符串
const allClasses = starEl.attr('class');
// 拆分后筛选出带count-的类
const countClass = allClasses.split(' ').find(cls => cls.startsWith('count-'));
// 最后提取星级数字,比如从count-3拿到3
const rating = countClass ? countClass.split('-')[1] : '无法获取评分';

2. Cheerio(Node.js 常用爬虫库)

如果用Node.js写爬虫,Cheerio的操作逻辑类似:

const cheerio = require('cheerio');
const $ = cheerio.load(你的HTML内容);

const starEl = $('.star-rating');
const classList = starEl.attr('class').split(' ');
// 筛选出包含count-的类
const countClass = classList.filter(cls => cls.includes('count-'))[0];
const rating = countClass ? countClass.split('-')[1] : 'N/A';

3. Python BeautifulSoup

用Python做爬虫的话,BeautifulSoup的处理方式也大同小异:

from bs4 import BeautifulSoup

soup = BeautifulSoup(你的HTML内容, 'html.parser')
star_el = soup.select_one('.star-rating')

if star_el:
    # 获取元素的所有类列表
    class_list = star_el.get('class', [])
    # 找到带count-的类
    count_class = next((cls for cls in class_list if 'count-' in cls), None)
    if count_class:
        rating = count_class.split('-')[1]
        print(f"提取到的星级:{rating}星")
    else:
        print("没找到带count-的类名")
else:
    print("定位不到star-rating元素")

小提醒

  • 要确认你的.star-rating选择器能精准定位到目标元素——有时候页面里可能有多个同名类,你可能需要加前置选择器缩小范围,比如.review-item .star-rating。
  • 如果Trustpilot的评分是动态加载的(比如滚动后才渲染),静态抓取HTML可能拿不到这些类名,这时候就得用Selenium、Playwright这类工具先渲染页面,再提取内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:32:34