一、响应内容信息获取
1、响应状态码
import requests
r = requests.get('https://api.github.com/some/endpoint')
print(r.status_code) #响应状态码
print(r.status_code==requests.codes.ok) #内置状态码查询对象
r.raise_for_status() #通过 Response.raise_for_status() 来抛出异常- 1
- 2
- 3
- 4
- 5
2、响应头信息
import requests
r = requests.get('http://httpbin.org/get')
print(r.headers) #获得响应头信息
print(r.headers['Content-Type'])
print(r.headers.get('Content-Length'))
>>`{'X-Processed-Time': '0.000617980957031', 'Connection': 'keep-alive', 'Via': '1.1 vegur', 'Content-Length': '268', 'X-Powered-By': 'Flask', 'Date': 'Thu, 23 Nov 2017 04:13:40 GMT', 'Server': 'meinheld/0.6.1', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Content-Type': 'application/json'}
>>application/json
>>268`- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
还有一个特殊点,那就是服务器可以多次接受同一 header,每次都使用不同的值。但 Requests 会将它们合并,这样它们就可以用一个映射来表示出来
3、如果某些请求包含cookie,可以使用以下命令获得cookie
获取响应信息中的cookie
import requests
r = requests.get('https://api.douban.com/v2/book/search?小王子')
print(r.cookies)
print(r.cookies['bid'])- 1
- 2
- 3
- 4
在发送请求时加入cookie参数
import requests
url= 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url,cookies=cookies)
print(r.text)- 1
- 2
- 3
- 4
- 5
4、请求信息获取r.request.headers
二、重定向与请求历史
import requests
r = requests.get('http://github.com')
print(r.history)
>>[<Response [301]>]- 1
- 2
- 3
- 4
通过 allow_redirects 参数禁用重定向处理
import requests
r = requests.get('http://github.com',allow_redirects=False)
print(r.status_code)
print(r.history)
>>301
>>[]- 1
- 2
- 3
- 4
- 5
- 6
使用head重启重定向
import requests
r = requests.head('http://github.com',allow_redirects=True)
print(r.url)
print(r.status_code)
print(r.history)- 1
- 2
- 3
- 4
- 5
三、准备请求(Prepared Request)
当从 API 或者会话调用中收到一个 Response 对象时,request 属性其实是使用了 PreparedRequest。有时在发送请求之前,你需要对 body 或者 header (或者别的什么东西)做一些额外处理
from requests import Request,Session
s = Session()
url='https://api.douban.com/v2/book/search'
data={'q':'小王子'}
header={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0'}
req = Request('GET',url,data=data,headers=header)
prepped = req.prepare()
resp = s.send(prepped,stream=stream,verity=verity,proxies=proxies,cert=cert,timeout=5)#可添加上述相关信息
print(resp.status_code)- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
上述代码会失去 Requests Session 对象的一些优势, 尤其 Session 级别的状态,例如 cookie 就不会被应用到你的请求上去。要获取一个带有状态的 PreparedRequest, 请用 Session.prepare_request() 取代 Request.prepare() 的调用
prepped = s.prepare_request(req)- 1
本文详细介绍了如何使用Python的requests库进行HTTP请求及响应处理,包括获取状态码、响应头信息、Cookie等,并展示了如何处理重定向及使用PreparedRequest进行请求定制。
2万+

被折叠的 条评论
为什么被折叠?



