爬取网络图片其实与爬取文本信息实质上没有太大的区别,在抓取网络图片的过程中主要需要确定网络图片的地址,图片的格式,图片的保存路径。
假定某网络图片的网络地址是http://img.xshuma.com/201309/161539130907740379.jpg
首先要对图片保存的命名方式进行设定,假设我要保存为161539130907740379.jpg,结合我之前分享过的关于字符串分割的博文,用split()方法一行代码就可以得到命名结果,保存图片的路径就自定义设置为D盘的某个文件夹D:\pics。
方法一【requests.get+open】:
import os
import requests
url = 'http://img.xshuma.com/201309/161539130907740379.jpg'
path = 'D://pics'
if not os.path.exists(path):
os.makedirs(path)
#设置图片保存位置
imgpath = path + '//' + os.path.split(url)[1]
try:
if not os.path.exists(imgpath):
#对网络图片地址发送get请求
t = r