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

如何使用requests.get通过参数而非完整路径发起请求

解决方法

你用json参数的方式不对,因为requests.get()里的json参数是用来把数据作为请求体发送的(通常适配POST请求),而GET请求的参数需要放在URL的查询字符串里,得用params参数来传递。

但要注意,目标接口要求的参数格式不是标准多值参数(比如select=name&select=numer),而是把多个值拼成带双引号的逗号分隔字符串,where参数也是特定格式的字符串,所以不能直接传列表或字典,得先把参数格式化成和原URL一致的字符串:

基础实现代码

import requests

# 完全复刻原URL的参数格式
params = {
    "select": '"name","numer"',
    "where": 'number="5"'
}

URL = "http://somepage.com"
response = requests.get(URL, params=params)

动态参数生成(适配可变字段/条件)

如果需要根据动态数据生成参数,可以写简单的格式化函数:

import requests

def format_select(fields):
    # 把字段列表转为带双引号的逗号分隔字符串
    return ",".join([f'"{field}"' for field in fields])

def format_where(conditions):
    # 把条件字典转为接口要求的 key="value" 格式(多条件需根据接口规则调整)
    key, value = next(iter(conditions.items()))
    return f'{key}="{value}"'

# 动态生成参数
select_fields = ["name", "numer"]
where_conditions = {"number": "5"}

params = {
    "select": format_select(select_fields),
    "where": format_where(where_conditions)
}

response = requests.get("http://somepage.com", params=params)

这样生成的请求URL会和你原来的完整URL格式完全一致,接口就能正常解析参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:32:14