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

如何用Python的Selenium通过Fetch请求实现带代理的自定义HTTP请求并获取JSON

使用Selenium发送带自定义HTTP头的请求并通过代理获取JSON响应

针对你遇到的两个问题,以下是具体解决方案和修正后的代码:

问题1:代理配置无效

Chrome的--proxy-server参数需要明确指定代理协议(如http://或socks5://),未指定协议会导致代理无法正确生效。修正后的代理配置需添加协议前缀:

chrome_options.add_argument(f'--proxy-server=http://{proxy_server_url}')

如果使用SOCKS代理,替换为socks5://前缀即可。同时可添加--no-sandbox参数,避免部分受限环境下的权限问题。

问题2:无法获取Fetch Promise的JSON结果

Selenium的execute_script无法直接处理异步Promise,需使用execute_async_script执行异步脚本,并通过回调函数将JSON数据传递回Python。具体实现需在JavaScript中等待Promise解析完成,再调用Selenium提供的回调返回结果。

完整修正代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

proxy_server_url = "127.0.0.1:8888"
chrome_options = webdriver.ChromeOptions()
# 修正代理参数,添加http://协议前缀
chrome_options.add_argument(f'--proxy-server=http://{proxy_server_url}')
chrome_options.add_argument("ignore-certificate-errors")
# 可选:禁用沙箱,适配部分受限环境
chrome_options.add_argument('--no-sandbox')

chrome = webdriver.Chrome(options=chrome_options)

try:
    # 先打开目标页面,确保浏览器上下文正确
    chrome.get("https://myhttpheader.com/")
    
    # 使用execute_async_script处理异步Fetch请求
    response_json = chrome.execute_async_script("""
        const callback = arguments[0];
        fetch('https://myhttpheader.com/', {
            method: 'GET',
            headers: {
                'Accept': '*/*',
                'Accept-Language': 'ru,en-US;q=0.9,en;q=0.8,ru-RU;q=0.7',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
                'Origin': 'https://myhttpheader.com',
                'Pragma': 'no-cache',
                'Referer': 'https://myhttpheader.com/',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin', // 当前页面与请求域名一致,修正为same-origin
                'CUSTOM_HEADER_1': 'value_1',
                'CUSTOM_HEADER_2': 'value_2'
            }
        })
        .then(response => {
            // 检查响应状态是否正常
            if (!response.ok) throw new Error(`请求失败,状态码:${response.status}`);
            return response.json();
        })
        .then(data => callback(data)) // 将JSON数据传递回Python
        .catch(error => callback({error: error.message})); // 捕获错误并返回
    """)
    
    print("响应JSON数据:")
    print(response_json)
    
finally:
    chrome.quit()

关键说明

  • 代理生效逻辑:添加协议前缀后,Chrome会将所有HTTP/HTTPS请求路由到指定代理服务器,此时代理工具(如Burp Suite、Charles)能正常捕获请求记录。
  • 异步脚本处理:execute_async_script的核心是通过arguments[0]获取Selenium注入的回调函数,在Promise的then或catch阶段调用该回调,实现Python与浏览器异步脚本的数据传递。
  • POST请求适配:若需发送POST请求,只需修改method为'POST',并添加body参数(需根据接口要求格式化数据,如JSON.stringify({key: "value"})),同时确保Content-Type头匹配数据格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:15:04