安装 Requests
打开终端,使用pip
安装
pip install requests
这可能会比较慢或者失败,如果失败可以尝试下面这个
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
如果你没有安装 pip
(啧啧),那就看下面的
下载zip包
git地址
获得源码之后可以解压到 python 包里,或者安装到你的 site-packages
然后回到终端,切换到该目录执行 python setup.py install
Requests基本使用
发送请求
>>>import requests
>>>r = requests.get('https://api.github.com/events')
>>>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')
传递 URL 参数
>>>payload = {'key1': 'value1', 'key2': 'value2'}#值为None则不添加
>>>r = requests.get("http://httpbin.org/get",params=payload)
>>>r.url
#http://httpbin.org/get?key2=value2&key1=value1
响应内容
>>>import requests
>>>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 #二进制响应内容
>>>r.json()#JSON相应内容
>>>r.raw #原始响应内容
>>>r.status_code#响应状态码
>>> r.status_code == requests.codes.ok
>>> r.raise_for_status()#如果是错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应)则抛出异常
定制请求头
header
值必须是 string
、bytestring
或者 unicode
>>>url = 'https://api.github.com/some/endpoint'
>>>headers = {'user-agent': 'my-app/0.0.1'}
>>>r = requests.get(url, headers=headers)
响应头
>>> r.headers#查看响应头
>>> r.headers['Content-Type']
#'application/json'
>>> r.headers.get('content-type')
#'application/json
Cookie
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')#设置
>>> r = requests.get(url, cookies=cookies)#发送
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
超时
>>> requests.get('http://github.com', timeout=1)
timeout 仅对连接过程有效,与响应体的下载无关
乱码问题
- 解决方案1
获取二进制数据,再利用str进行编码转换
r = requests.get(url)
html=r.content
html_=str(html,'utf-8')
print(html_)
- 解决方案2
使用encoding
属性
r=requests.get(url)
r.encoding='utf-8'
print(r.text)
- 解决方案3
使用apparent_encoding
方法
r=requests.get(url)
print(r.apparent_encoding)
r.encoding=r.apparent_encoding
print(r.text)
错误与异常
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError
异常
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status()
会抛出一个 HTTPError
异常
若请求超时,则抛出一个 Timeout
异常
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects
异常
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException