Response响应相关

response是响应的对象

 

response.text      # 返回的是字节,数据的原内容
response.content # 返回的是字符串,默认是utf-8解码

import requests

response = requests.get('http://httpbin.org/get')

t1 = response.text              # 返回是str类型的数据
t2 = response.content           # 返回是bytes类型的数据

 

重定向:浏览器发送请求,服务器返回重定向的状态码和location,没有响应体。浏览器会自动再发送给location的url一次请求,才能得到响应体

 

respone.status_code     # 返回状态码
respone.headers         # 返回的是响应头
respone.url          # 返回最后请求的URL

response.history                      # 默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的 history 方法来追踪重定向。Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

response = requests.get('http://www.jd.com',allow_redirects=False)      # 禁止重定向
print(response.status_code)         # 302
print(response.url)                 # http://www.jd.com/
print(response.history)             # []

response = requests.get('http://www.jd.com')
print(response.status_code)         # 200
print(response.url)                 # https://www.jd.com/
print(response.history)             # [<Response [302]>]

 

respone.cookies           # 返回对象
respone.cookies.get_dict()       # 返回字典格式
respone.cookies.items()        # 返回列表格式,里面是一个个元组

response = requests.get("https://github.com/login")
print(response.cookies)           # 返回一个对象

print(response.cookies.get_dict())  # 返回字典格式 {'logged_in': 'no'}
print(response.cookies.items())     # 返回列表格式 [('logged_in', 'no'),]

 

respone.encoding                     # 用于解码

response = requests.get('https://www.autohome.com.cn/beijing/')
response.encoding = 'gbk'       # 指定编码

with open('qiche.html','w') as f:
    f.write(response.text)

 

下载二进制资源(图片、视频、音频)

response.iter_content() 

response = requests.get('http://img.ivsky.com/img/tupian/pre/201808/02/xunyicao-002.jpg')

with open('fengjing.jpg','wb') as f:
    for line in response.iter_content():        # response.iter_content(),返回一个迭代器
        f.write(line)

 

解释json数据

response.json()            # 将数据反序列化

import requests
import json


cookies = {"a":"1","b":"2"}
response = requests.get('http://httpbin.org/cookies',cookies=cookies)
dic1 = json.loads(response.text)        # 将字符串反序列化为字典格式 {'cookies': {'a': '1', 'b': '2'}}
dic2 = response.json()         

 

 

使用代理

requests.get('http://httpbin.org/ip', proxies={'http':'110.83.40.27:9999'})

 

posted @ 2019-01-22 20:57  st--st  阅读(612)  评论(0编辑  收藏  举报