Python 请求 - 通过 GET 传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50737866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:35:23  来源:igfitidea点击:

Python Requests - pass parameter via GET

pythongetrequestpython-requests

提问by Cody Raspien

I am trying to call an API and pass some parameters to it.

我正在尝试调用 API 并向其传递一些参数。

My endpoint should look like:

我的端点应如下所示:

https://example.com?q=foodfood is the parameter

https://example.com?q=foodfood 是参数

import requests
parametervalue = "food"
r = requests.get("https://example.com/q=", parametervalue)

When I do print r.url, I do not get the correct result - the value is not passed.

当我打印 r.url 时,我没有得到正确的结果 - 没有传递值。

Updated:

更新:

Error:

错误:

  r = requests.get('https://example.com', params={'1':parametervalue})
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 55, in get
  return request('get', url, **kwargs)

Update:

更新:

Answer posted below. Thank you.

答案贴在下面。谢谢你。

Note: The SSL error mentioned in the post was due to me running Python 2.7. I used python3 and it fixed the issue.

注意:帖子中提到的 SSL 错误是由于我运行的是 Python 2.7。我使用了 python3,它解决了这个问题。

回答by Pitto

Here's the relevant code to perform a GET http call from the official documentation

这是从官方文档中执行 GET http 调用的相关代码

import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)

In order to adapt it to your specific request:

为了使其适应您的特定要求:

import requests
payload = {'q': 'food'}
r = requests.get('http://httpbin.org/get', params=payload)
print (r.text)

Here's the obtained result if I run the 2nd example:

如果我运行第二个示例,这是获得的结果:

python request_test.py
{"args":{"q":"food"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.1"},"origin":"x.y.z.a","url":"http://httpbin.org/get?q=food"}