You need to enable JavaScript to run this app. 如何用Python获取Target网页动态HTML实现商品库存自动检测
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取Target网页动态HTML实现商品库存自动检测

问题原因
  • urllib默认发送的请求不带浏览器标识,会被Target的反爬策略识别为爬虫,返回的不是普通用户访问的正常页面
  • Target商品页的Get it by这类配送、库存相关文本是JavaScript动态渲染生成的,urllib只能拿到页面初始的静态HTML,不会执行JS加载后续动态内容,自然无法匹配到对应文本
  • 浏览器检查元素中展示的是所有JS执行完毕、页面完全渲染后的最终DOM内容,和urllib拿到的初始静态HTML本身就存在很大差异
实现方案

方案1:无头浏览器模拟访问(最稳定,推荐)

使用Playwright或Selenium这类无头浏览器工具,完全模拟浏览器的页面加载、JS执行流程,就能拿到和浏览器检查元素一致的完整页面内容。

依赖安装

pip install playwright
playwright install chromium

检测代码

from playwright.sync_api import sync_playwright

target_substring = 'Get it by'
# 替换为需要检测的商品链接
product_url = "https://www.target.com/p/dualsense-wireless-controller-for-playstation-5/-/A-83377785?preselect=81114477#lnk=sametab"

with sync_playwright() as p:
    # 启动无头Chromium,模拟普通用户浏览器参数
    browser = p.chromium.launch(headless=True)
    context = browser.new_context(
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        viewport={"width": 1920, "height": 1080}
    )
    page = context.new_page()
    # 访问页面,等待网络空闲确保基础内容加载完成
    page.goto(product_url, wait_until="networkidle")
    # 额外等待2秒确保动态库存内容渲染完成
    page.wait_for_timeout(2000)
    full_page_content = page.content()

    if target_substring in full_page_content:
        print('in stock')
    else:
        print('oos')

    browser.close()

方案2:调用库存查询接口(性能更高)

如果需要批量检测不想启动浏览器,可以在浏览器的网络面板里过滤fulfillment、inventory相关的请求,找到Target官方的库存查询接口,带上和浏览器一致的请求头、参数直接调用接口,解析返回的JSON结果判断库存即可,效率比加载整个页面高很多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 04:00:01