参考:https://www.icourse163.org/learn/BIT-1001870001?tid=1464881473#/learn/content
安装
pip install requests
import requests
Response对象
方法
request()
基础方法
def request(method, url, **kwargs):
get()
def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:return: :class:`Response <Response>` object
"""
head()
def head(url, **kwargs):
"""Sends a HEAD request."""
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
post()
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
example:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post('http://httpbin.org/post', data = payload)
>>> print(r.text)
{ ...
"form": {
"key2": "value2",
"key1": "value1"
},
}
put()
patch()
delete()
**kwargs:
参数 | 内容 |
---|---|
params | 字典或字节序列,作为参数增加到url中 |
data | 字典、字节序列或文件对象,作为Request的内容 |
json | JSON格式的数据,作为Request的内容 |
headers | 字典,HTTP定制头 |
cookies | 字典或CookieJar,Request中的cookie |
auth | 元组,支持HTTP认证功能 |
files | 字典类型,传输文件 |
timeout | 设定超时时间,秒为单位 |
proxies | 字典类型,设定访问代理服务器,可以增加登录认证 |
allow_redirects | True/False,默认为True,重定向开关 |
stream | True/False,默认为True,获取内容立即下载开关 |
verify | True/False,默认为True,认证SSL证书开关 |
cert | 本地SSL证书路径 |
异常
异常 | 说明 |
---|---|
requests.ConnectionError | 网络连接错误异常,如DNS查询失败、拒绝连接等 |
requests.HTTPError HTTP | 错误异常 |
requests.URLRequired | URL缺失异常 |
requests.TooManyRedirects | 超过最大重定向次数,产生重定向异常 |
requests.ConnectTimeout | 连接远程服务器超时异常 |
requests.Timeout | 请求URL超时,产生超时异常 |
Response对象
属性
属性 | 说明 |
---|---|
r.status_code | HTTP请求的返回状态 |
r.text | HTTP响应内容的字符串形式,即,url对应的页面内容 |
r.encoding | 从HTTP header中猜测的响应内容编码方式 |
r.apparent_encoding | 从内容中分析出的响应内容编码方式(备选编码方式) |
r.content | HTTP响应内容的二进制形式 |
方法
raise_for_status()
def raise_for_status(self):
"""Raises :class:`HTTPError`, if status_code != 200."""