我似乎无法谷歌它,但我想要一个这样做的函数:
接受 3 个参数(或更多,随便):
- 网址
- 参数字典
- POST 或 GET
将结果和响应代码返回给我。
有这样的片段吗?
最佳答案
请求
https://github.com/kennethreitz/requests/
以下是几种常用的使用方法:
import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}
# GET
r = requests.get(url)
# GET with params in URL
r = requests.get(url, params=payload)
# POST with form-encoded data
r = requests.post(url, data=payload)
# POST with JSON
import json
r = requests.post(url, data=json.dumps(payload))
# Response, status etc
r.text
r.status_code
httplib2
https://github.com/jcgregorio/httplib2
>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT',
'content-type': 'text/html'}
关于python - Python 中的简单 URL GET/POST 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4476373/