Python请求 - 通过GET传递参数

时间:2018-06-07 09:34:59

标签: python get request python-requests

我正在尝试调用API并将一些参数传递给它。

我的端点应如下所示:

https://example.com?q=food 食物是参数

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

当我打印r.url时,我没有得到正确的结果 - 该值未通过。

更新:

错误:

  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)

更新

下面发布的答案。谢谢。

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

1 个答案:

答案 0 :(得分:6)

以下是从official documentation

执行GET http调用的相关代码
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)

为了使其适应您的具体要求:

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

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

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":"62.182.241.13","url":"http://httpbin.org/get?q=food"}