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'})

 

转载于:https://www.cnblogs.com/st-st/p/10306036.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值