文章

requests库基础

开始

requests库是Python中常用的HTTP请求库

安装requests

1
pip install requests

发送请求

requests中支持多种HTTP的请求方法

1
2
3
4
5
6
response = requests.get('https://api.github.com/events')  # get方法
response = requests.post('http://httpbin.org/post', data = {'key':'value'})  # post方法
response = requests.put('http://httpbin.org/put', data = {'key':'value'})  # put方法
response = requests.delete('http://httpbin.org/delete')  # delete方法
response = requests.head('http://httpbin.org/get')  # head方法
response = requests.options('http://httpbin.org/get')  # options方法

获取响应

requests请求方法返回一个Response对象,通过该对象获取响应

常用属性/方法描述
text响应文本内容
content响应内容的二进制形式
status_code响应状态码
headers响应头字典
encoding响应的编码方式,响应头的Content-Type字段
cookies响应中包含的cookie字典
reason响应状态码相对应的描述文本
url最终响应的url
raw响应的原始HTTPResponse对象
history当前请求的响应历史(重定向)
elapsed从发送请求到响应到达的时间
request响应的请求对象
json()若响应中的内容是json字符串时,将json字符串解码为字典类型
raise_for_status()当状态码为4XX或5XX时,该方法抛出异常

请求设置

设置请求头

在请求方法的headers参数传入一个字典,字典中可以设置请求头字段

1
2
3
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
response = requests.get(url, headers=headers)

参数传递

对于get请求,在get方法的params参数传入一个字典,可以传递url参数

1
2
3
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://httpbin.org/get', params=payload)
# http://httpbin.org/get?key2=value2&key1=value1

对于post请求,在post方法的data参数传入一个字典,可以传递表单数据

1
2
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post("http://httpbin.org/post", data=payload)

data参数可以接收一个json格式的字符串,自动解码为字典,或json参数可以接收一个字典,自动编码为json字符串

1
2
3
4
5
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
r = requests.post(url, json=payload)

通过files参数上传文件

1
2
3
4
5
url = 'http://www.example.com/upload'
headers = {'Content-Type': 'multipart/form-data'}
files = {'file': open('example.txt', 'rb')}  # 设置文件数据

response = requests.post(url, files=files, headers=headers)

在请求方法的cookies参数中传入一个字典即可在请求中包含cookie

1
2
3
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)

cookies参数还可以传入一个RequestsCookieJar对象,类似一个字典,但包含更多接口

1
2
3
4
5
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)

通过response对象的cookies属性可以获取响应中的cookie,cookies属性返回一个字典

1
2
3
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']

超时

在请求方法中设置timeout参数来设置超时时间,当请求超时,不再等待响应,抛出Timeout异常

1
requests.get('http://github.com', timeout=0.001)

其他异常

requests中抛出以下常见异常

  • 遇到网络问题(如:DNS查询失败、拒绝连接等)时,requests会抛出一个ConnectionError异常
  • 如果HTTP请求返回了不成功的状态码,raise_for_status()会抛出一个HTTPError异常
  • 若请求超时,则抛出一个Timeout异常
  • 若请求超过了设定的最大重定向次数,则会抛出一个TooManyRedirects异常
本文由作者按照 CC BY 4.0 进行授权