如何使用Selenium监控网络流量并获取API响应?
使用Selenium获取Shopee商品API响应的方法
针对你需要获取Shopee商品详情API响应的需求,下面提供两种基于Selenium的可行方案:
方案一:通过Chrome DevTools Protocol(CDP)监听网络请求
利用Selenium结合Chrome开发者工具协议,拦截并捕获目标API的响应数据:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import json # 初始化Chrome浏览器配置 chrome_options = Options() chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) driver = webdriver.Chrome(options=chrome_options) driver.execute_cdp_cmd("Network.enable", {}) # 定义监听函数,过滤目标API def capture_api_response(params): request_id = params["requestId"] response = params["response"] if "api/v4/item/get" in response["url"]: # 获取响应体 body = driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id}) api_data = json.loads(body["body"]) print("API响应数据:", api_data) # 保存数据到文件 with open("shopee_item_data.json", "w", encoding="utf-8") as f: json.dump(api_data, f, ensure_ascii=False, indent=2) # 绑定监听事件 driver.add_cdp_listener("Network.responseReceived", capture_api_response) # 加载目标商品页面 target_url = "https://shopee.co.id/PANCI-PRESTO-24cm-3.5L-TEFLON-i.323047288.19137193916?sp_atk=7e8e7abc-834c-4f4a-9234-19da9ddb2445&xptdk=7e8e7abc-834c-4f4a-9234-19da9ddb2445" driver.get(target_url) # 等待页面加载完成 driver.implicitly_wait(10) # 关闭浏览器 driver.quit()
方案二:直接执行JavaScript发起API请求
通过Selenium的execute_script方法,在浏览器环境中直接调用目标API,跳过页面冗余加载:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import json chrome_options = Options() chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) driver = webdriver.Chrome(options=chrome_options) # 先加载Shopee主页确保会话有效 driver.get("https://shopee.co.id") driver.implicitly_wait(5) # 执行JavaScript调用API api_url = "https://shopee.co.id/api/v4/item/get?itemid=19137193916&shopid=323047288" script = f""" return fetch('{api_url}', {{ method: 'GET', credentials: 'include' }}).then(response => response.json()); """ api_response = driver.execute_script(script) print("API响应数据:", api_response) # 保存数据到文件 with open("shopee_item_data.json", "w", encoding="utf-8") as f: json.dump(api_response, f, ensure_ascii=False, indent=2) driver.quit()
注意事项
- Shopee存在反爬机制,建议添加合理等待时间,避免高频请求;
- 部分API需要有效会话Cookie,提前加载Shopee主页可确保会话正常;
- 若请求被拦截,可额外添加浏览器指纹伪装参数(如自定义User-Agent、语言设置等)。
内容的提问来源于stack exchange,提问作者user17575870
相关产品推荐
相关产品推荐

