Requests学习

本文详细介绍了Python的Requests库如何处理网络请求,包括GET方法的使用、不同解码方式的对比,以及如何处理二进制数据如图片。通过具体代码示例,展示了Requests库在网页数据抓取和图片下载方面的应用。
摘要由CSDN通过智能技术生成

Requests.get(url,params=params)

Requests中解决解码的方法

response=requests.get('https://www.ssyer.com/')
response.content.decode()        #推荐这种方式获取网页数据
response.content.decode('gbk')
response.text
  • 使用response.text 时,Requests 会基于 HTTP 响应的文本编码自动解码响应内容,大多数 Unicode 字符集都能被无缝地解码。若accept-encoding 不存在,则会使用 chardet.detect来尝试猜测编码方式(存在误差)

  • Requests使用response.content 时,返回的是服务器响应数据的原始二进制字节流,可以用来保存图片等二进制文件。(requests自带解压压缩网页的功能,推荐response.content.deocde()

例子:

#coding=utf-8
import  requests
response = requests.get("http://www.sina.com")
print(response.request.headers)
print(response.content.decode())
from io import BytesIO,StringIO
# StringIO:内存中读写str。
# BytesIO:内存中读写bytes类型的二进制数据
# import requests
from PIL import Image
img_url = "https://ssyerv1.oss-cn-hangzhou.aliyuncs.com/picture/440677cccbce4675b7866611a0c6fad7.jpg!sswm"
response = requests.get(img_url)
f = BytesIO(response.content)
img = Image.open(f)
print(img.size)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值