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

如何使用Python Selenium发送POST请求?

Python Selenium 发送POST请求的实现方案

Selenium本身定位为浏览器交互模拟工具,没有原生的POST请求发送接口,你可以根据需求选择以下三种常用实现方案:

方法1:执行JS发送AJAX请求(推荐)

直接在当前页面上下文运行JS的fetch方法,会自动携带当前页面的cookies、UA等环境信息,完全模拟浏览器原生请求逻辑:

from selenium import webdriver

driver = webdriver.Chrome()
# 提前打开目标站点同域页面,避免跨域限制
driver.get("https://目标站点域名/任意可访问页面")

# 替换为你准备好的接口地址和参数
post_url = "目标POST接口地址"
post_data = {
    "参数1键": "参数1值",
    "参数2键": "参数2值"
}

# 执行JS发送请求,返回接口响应内容
response = driver.execute_script("""
    return fetch(arguments[0], {
        method: 'POST',
        headers: {
            // 可根据开发者工具里的实际请求头修改Content-Type
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        // 如果接口接收JSON格式参数,替换为:body: JSON.stringify(arguments[1])
        body: new URLSearchParams(arguments[1]).toString()
    }).then(res => res.text())
    // 如果返回是JSON格式,替换为:.then(res => res.json())
""", post_url, post_data)

print(response)

方法2:动态构造表单提交

适合需要模拟表单提交后跳转页面的场景:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://目标站点域名/任意可访问页面")

post_url = "目标POST接口地址"
post_data = {
    "参数1键": "参数1值",
    "参数2键": "参数2值"
}

# 生成隐藏表单并提交
driver.execute_script("""
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = arguments[0];
    Object.entries(arguments[1]).forEach(([k, v]) => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = k;
        input.value = v;
        form.appendChild(input);
    });
    document.body.appendChild(form);
    form.submit();
""", post_url, post_data)

# 提交后Selenium会自动跳转到接口返回的页面,可直接进行后续页面操作

方法3:复用Selenium Cookie结合requests发送请求

如果你不需要页面交互,只需要复用Selenium的登录态,可以导出Cookie给requests使用:

import requests
from selenium import webdriver

driver = webdriver.Chrome()
# 先完成目标站点的登录操作,拿到有效登录态
driver.get("https://目标站点登录后页面")

# 导出Selenium当前的Cookie
cookies = {item['name']: item['value'] for item in driver.get_cookies()}

post_url = "目标POST接口地址"
post_data = {"参数1键": "参数1值"}
# 发送请求,和直接用Selenium发送的请求登录态完全一致
response = requests.post(post_url, data=post_data, cookies=cookies)
print(response.text)

注意事项

  • 你可以通过下图的Chrome开发者工具查看接口的实际请求头、参数格式,调整上述代码中的配置,和真实请求保持完全一致
  • 用JS发送请求需要保证当前页面和目标接口同域,提前打开目标站点任意页面即可规避跨域限制

Chrome开发者工具

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:08