request模块简介
request模块
一、安装
● pip install requests
● 在开发工具中安装
二、request常用方法
● requests.get(网址)
三、响应对象response的方法
● response.text 返回unicode格式的数据(str)
● response.content 返回字节流数据(二进制)
● response.content.decode(‘utf-8’) 手动进行解码
● response.url 返回url
● response.encode() = ‘编码’
保存图片案例
request模块 保存图片
首先导入request模块,然后向url发送get请求
import requests
url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F11012685795%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651324072&t=b712c65bdf48d9979a572572a72b7d4b"
img_name = 'code.png'
# 发送请求
res = requests.get(url)
print(res.content)
request模块 第一种保存图片的方式
通过with open来将图片保存
# 保存图片、音频之类会使用wb-->以二进制的方式写入
with open(img_name, 'wb') as file_obj:
# 保存图片、音频之类 会使用content-->以二进制写入去响应对象里面取
file_obj.write(res.content)
request模块 第二种保存图片的方式
通过open来将图片保存
# file_obj是一个文件对象
file_obj = open(img_name,'wb')
file_obj.write(res.content)
# 没用with 要手动关闭
file_obj.close()
urllib模块 保存图片
首先导入urllib模块
import urllib.request
url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F11012685795%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651324072&t=b712c65bdf48d9979a572572a72b7d4b"
img_name = 'code3.png'
第一种导入方式,以及第一种保存图片方式
可以通过书写指定地址将图片保存
file_name = r'F:\pycharm program\pythonProject\爬虫\code4.png'
urllib.request.urlretrieve(url,file_name)
第二种导入方式,以及第二种保存图片方式
通过直接给图片命名,保存在当前文件目录下
import urllib.request
urllib.request.urlretrieve(url,img_name)
完整代码如下:
import requests
import urllib.request
url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F11012685795%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651324072&t=b712c65bdf48d9979a572572a72b7d4b"
img_name = 'code3.png'
# 发送请求
# res = requests.get(url)
# print(res.content)
# # request模块 第一种保存图片的方式
# # 保存图片、音频之类会使用wb-->以二进制的方式写入
# with open(img_name, 'wb') as file_obj:
# # 保存图片、音频之类 会使用content-->以二进制写入去响应对象里面取
# file_obj.write(res.content)
# request模块 第二种保存图片的方式
# # file_obj是一个文件对象
# file_obj = open(img_name,'wb')
# file_obj.write(res.content)
# # 没用with 要手动关闭
# file_obj.close()
#urllib模块
'''
url 是图片的url地址
img_name 是图片的保存的名字
'''
# 第一种导入方式,以及第一种保存图片方式
from urllib import request
file_name = r'F:\pycharm program\pythonProject\爬虫\code4.png'
urllib.request.urlretrieve(url,file_name)
# 第二种导入方式,以及第二种保存图片方式
import urllib.request
urllib.request.urlretrieve(url,img_name)