Skip to content

Instantly share code, notes, and snippets.

@Xifeng2009
Created January 8, 2019 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xifeng2009/f10ebf23f82f67ad4670b7473ed695b9 to your computer and use it in GitHub Desktop.
Save Xifeng2009/f10ebf23f82f67ad4670b7473ed695b9 to your computer and use it in GitHub Desktop.
import requests
# GET请求
r = requests.get('https://api.github.com/events')
# POST请求
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
# 其他
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')
# GET参数传递
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
# >>> http://httpbin.org/get?key2=value2&key1=value1
# 传入列表
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
>>> r.url
>>> http://httpbin.org/get?key1=value1&key2=value2&key2=value3
# 响应内容
r = requests.get('https://api.github.com/events')
>>> r.text
>>> u'[{"repository":{"open_issues":0,"url":"https://github.com/...
>>> r.encoding
>>> 'utf-8'
>>> r.encoding = 'ISO-8859-1'
# 二进制响应内容
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
# JSON响应内容
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
# 原始响应内容
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
# 将文本流保存到文件
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
# 定制请求头
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
# 更复杂的POST请求
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
文档:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment