You need to enable JavaScript to run this app. 使用requests与BeautifulSoup抓取H&M商品页价格的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

使用requests与BeautifulSoup抓取H&M商品页价格的实现方法

核心问题原因

你之前的检索条件和页面实际DOM属性完全错位:从给出的结构可以看到,id="product-price"是自定义标签<hm-product-price>的属性,不是你代码里检索的<span>标签的属性,自然匹配不到任何结果。

可直接使用的价格提取实现

结合已明确的DOM层级,有两种稳定性较高的提取方案:

  • 方案1:通过已知id锚定父节点,再向下提取价格文本
    对应代码:
    # 定位挂载product-price id的自定义标签容器
    price_parent = soup.find('hm-product-price', id='product-price')
    # 在容器范围内提取span中的价格文本
    price = price_parent.find('span').get_text().strip()
    print(price)
    
  • 方案2:直接匹配价格区块的固定class定位元素
    对应代码:
    price = soup.find('div', class_='ProductPrice-module--productItemPrice__2i2Hc').get_text().strip()
    print(price)
    

注意:请求头中的User-Agent需要替换为真实浏览器的UA字符串,否则容易触发网站反爬机制,拿到的是不完整的验证页内容,哪怕定位逻辑完全正确也无法解析到对应元素。

内容的提问来源于stack exchange,提问作者no0b.c0der2020

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 21:36:04