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

如何用Python Requests模块判断页面使用GET或POST请求方法

用Python的requests判断目标接口支持的请求方法

先说明白:网页/接口不是固定“用”GET或POST的,得看服务器端配置了允许该接口接收哪种请求方法。下面给两种靠谱的实现方式:

方法一:发OPTIONS请求直接获取允许的方法

HTTP的OPTIONS请求专门用来查询服务器:这个URL允许使用哪些请求方法?返回的响应头里有个Allow字段,直接读取就能拿到结果:

import requests

def check_allowed_methods(url):
    try:
        resp = requests.options(url)
        allowed_methods = resp.headers.get('Allow', '').split(', ')
        # 按需返回结果:可以是布尔值,也可以直接返回方法名
        if 'GET' in allowed_methods and 'POST' in allowed_methods:
            return "GET、POST都支持"
        elif 'GET' in allowed_methods:
            return "GET"
        elif 'POST' in allowed_methods:
            return "POST"
        else:
            return "不支持GET/POST"
    except requests.exceptions.RequestException as e:
        return f"请求出错:{str(e)}"

# 使用示例
url = "https://www.example.com"
print(check_allowed_methods(url))

方法二:直接发送GET/POST请求测试

分别发送GET和POST请求,通过响应状态码判断是否支持(一般返回2xx范围的状态码就算支持),不过这种方法准确性稍差,因为部分接口需要传入特定参数才会正常响应:

import requests

def test_request_methods(url):
    supports_get = False
    supports_post = False

    # 测试GET请求
    try:
        get_resp = requests.get(url)
        if 200 <= get_resp.status_code < 300:
            supports_get = True
    except:
        pass

    # 测试POST请求
    try:
        post_resp = requests.post(url)
        if 200 <= post_resp.status_code < 300:
            supports_post = True
    except:
        pass

    # 返回布尔值结果
    return {"GET支持": supports_get, "POST支持": supports_post}

# 使用示例
url = "https://www.example.com"
print(test_request_methods(url))

注意点

  • 有些服务器会禁用OPTIONS请求,这时就只能用第二种方法测试
  • 你提供的示例里response.check_get是不存在的属性,requests的Response对象没有这个方法,得通过上述方式实现
  • 部分POST接口需要传入必填参数,否则会返回400类错误,这种情况要根据接口实际要求添加参数后再测试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:35:02