简体   繁体   English

如何将查询字符串传递给request.get的参数?

[英]How to pass query strings for to params for requests.get?

Given is a string: 给定一个字符串:

'search=hello+world&status=something&cache=false' 

How do I pass parameters and values from that string to a payload dictionary given that I'm not sure what parameters I will always get from the string in order to use it in requests.get()? 如果不确定我将始终从字符串中获取哪些参数以便在requests.get()中使用它,那么如何将参数和值从该字符串传递至有效负载字典?

requests.get(url, params=payload, headers=headers)

you can give as follows 你可以给出如下

 url = url + '?'+ your_parm_string r = requests.get(url, headers=headers) 
string = 'search=hello+world&status=something&cache=false'
params = string.split('&')
payload = {}
for params in param:
    p = param.split('=')
    payload[p[0]] = p[1]
print(payload)
{'search': 'hello+world', 'status': 'something', 'cache': 'false'}

Use a dict comprehension : 使用dict 理解

def split_params(param_string):
   return {param: value for param, value in (pair.split('=') for pair in param_string.split('&'))}

split_params('search=hello+world&status=something&cache=false')

Output: 输出:

{'search': 'hello+world', 'status': 'something', 'cache': 'false'}

This is based off the observation that each param-value pair is separated externally by an & and internally by an = . 这是基于以下观察:每个参数值对在外部用&分隔,在内部用=分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM