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

如何使用BeautifulSoup定位乐天(Rakuten)网站的评分数量元素

提问内容

我无法在乐天(Rakuten)网站找到星级旁的评分数量,相关示例图片如下:
乐天网站评分位置示例图

我尝试使用beautifulsoup定位该元素,但运行后没有成功获取到对应内容。

我当前使用的代码如下:

import time
import requests
!pip install beautifulsoup4
import bs4
!pip install lxml
from bs4 import BeautifulSoup
import pandas as pd

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'}

products =[]
for i in range(1,2): # 遍历从第1页到最后一页的商品列表
    url = "https://www.rakuten.com.tw/shop/pandq/product/?l-id=tw_shop_inshop_cat&p={}".format(i)
    r = requests.get(url, headers = headers)
    soup = bs4.BeautifulSoup(r.text,"lxml")

    Soup = soup.find_all("div",class_='b-mod-item-vertical products-grid-section')

    for product in Soup:
        productcount = product.find_all("div",class_='b-content')
        print(productcount)

请问我该如何调整代码才能正确定位到评分数量的对应元素?


解答

问题原因

你通过requests获取的是页面静态HTML源码,其中不包含评分数量数据,这类数据是页面加载完成后通过JavaScript动态渲染填充的,所以BeautifulSoup直接解析静态页面找不到对应元素。

调整方案

推荐直接调用页面内部的商品列表接口获取结构化数据,不需要解析前端页面,效率更高:

import requests
import pandas as pd

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest'
}

products = []
# 可自行调整页数范围
for page in range(1, 5):
    # 店铺商品列表异步接口
    api_url = f"https://www.rakuten.com.tw/shop/pandq/product/?l-id=tw_shop_inshop_cat&p={page}&ajax=1"
    resp = requests.get(api_url, headers=headers)
    data = resp.json()
    # 遍历提取商品信息
    for item in data['Products']:
        product_info = {
            '商品名称': item['itemName'],
            '商品价格': item['itemPrice'],
            '评分星级': item['reviewAverage'],
            '评分数量': item['reviewCount']
        }
        products.append(product_info)
        print(f"商品:{product_info['商品名称'][:20]}...,评分数量:{product_info['评分数量']}")

# 数据导出为Excel
df = pd.DataFrame(products)
df.to_excel('乐天商品评分数据.xlsx', index=False)

备选方案

如果一定要使用页面解析的方式,需要将requests替换为Selenium、Playwright这类支持动态页面渲染的工具,等页面完全加载完成后再提取HTML内容交给BeautifulSoup解析即可。


内容的提问来源于stack exchange,提问作者鄭鼎彥

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:03