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

如何使用Python访问HTML页面变量获取欧尚网站商品库存信息

解决方案
  • 你已经正确定位到了存储目标字段的第4个script标签,该标签内容为前端JS代码,BeautifulSoup无法直接解析JS内部变量,需先提取script标签的文本内容,再通过正则匹配提取productStockLevel字段值。
  • 请求时需携带User-Agent请求头模拟浏览器访问,避免触发网站反爬策略返回异常内容。
可运行修改代码
import requests
import re
from bs4 import BeautifulSoup

session = requests.session()
# 模拟浏览器请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}

def get_stock():
    global session
    productPage = 'https://www.auchan.fr/power-a-etui-de-protection-silhouette-pikachu-nintendo-switch/p-c1334312'
    response = session.get(productPage, headers=headers)
    if response.status_code != 200:
        print(f"请求失败,状态码:{response.status_code}")
        return
    soup = BeautifulSoup(response.content, "html.parser")
    # 提取script标签内的JS文本
    script_text = soup.find_all('script')[4].string
    # 正则匹配库存字段
    stock_match = re.search(r'productStockLevel\s*:\s*"([^"]+)"', script_text)
    if stock_match:
        stock_status = stock_match.group(1)
        print(f"库存状态:{stock_status}")
        return stock_status
    print("未找到库存字段")
    return None

get_stock()
实现说明
  • 新增浏览器请求头,规避基础反爬拦截
  • 通过.string属性提取script标签内的纯JS代码文本
  • 正则表达式中\s*适配变量名与值之间的任意空格,兼容JS代码的格式差异
  • 增加请求状态与匹配结果校验,避免运行异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 02:00:05