Python的功能很强大,废话不多说,关于如何爬取网络上的图片,并且保存到本地文件夹,第一步要先获得网页的html源码,因为
图片地址都是在网页的html源码中,若干图片可能隐藏在js中(先不考虑)
一:获取网页的html源码(注:Python3要用urllib.request库,python2只要用urllib2库)这里用的是urllib.reuqest库
import urllib.request
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read() #urllib用read()读取html;requests包用text读取html
print(html)
return html.decode('UTF-8')#编码格式响应的转换
二:获得图片对应得src或者是http连接
import re #导入所需的正则包
def getImg(html):
src = r'src="(.+?\.jpg)"' 一个万能的表达式,''之间是匹配的值,详情可以参考正则表达式的详情
https://blog.csdn.net/qq_878799579/article/details/72887612
imgre = re.compile(src) #re.compile(),可以把正则表达式编译成一个正则表达式对象,通俗点就是匹配对应的正则
imglist = imgre.findall(html) #列表自己定义的空列表,用对象.findall来查找对应的src值并且保存到列表中
#re.findall(),读取html中包含imgre(正则表达式)的数据,imglist是包含了所有src元素的数组
print(imglist) #可以校验是否存在值
#用urlretrieve下载图片。图片命名为0/1/2...之类的名字,首先需要把图片的名字规范,每一张不一样,定义变量
x= 0
#打开imglist中保存的图片地址,并下载图片至本地,format格式化字符串
for urlimg in imglist: #遍历列表,比较常用的一个方法
urllib.request.urlretrieve(urlimg, 'D:\python image\%s.jpg' % x)
x+=1
return imglist
#调用函数
html = getHtml("https://www.csdn.net/")
getImg(html)
print('OK')
pycharm控制台的结果显示:

本地文件夹的显示:

三:接口测试的实战(关于接口返回值的图片信息的采集)
对于一个可以返回图片信息的接口,想要抓去它的图片地址,并且保存至本地,首先要把返回值中的图片的字段拿出来
再取得所有的返回值后,才执行下面操作(小编是用了循环,一页页拿返回值,遍历过去的)
for value in response2['content']['data']: #该返回值值data里的image属性,可以通过先拿出data数组,再拿image属性
if value['image']=='': #判断空的返回值,有些iamge为空,没有头像,在下面保存至本地会出错
pass
else:
picture.append(value['image']) #把图片拿出来,picture定义的空列表
namelist.append(value['userId']) #把相应的名字也拿出来,给图片命名,namelist定义的空列表
#保存至本地路径(万能的方法)
dir_name = 'D:\python image' #自定义路径
for urllim in picture:
pic = namelist[x] #将列表的下标相对应的
if not os.path.exists(dir_name): #导入OS,判断目录是否存在,如果不存在创建,利用makedirs方法
os.makedirs(dir_name)
# print('yes')
urllib.request.urlretrieve(urllim,'D:\python image\%s.jpg' % pic)
# print('yes')
x+=1
附:详细代码
# -*- coding: utf-8 -*
import json
import requests
import re
import urllib.request
import os
picture = []
currentpage = 0
namelist = []
url = '自己替换'
para = {"size": 1,
"page": 0}
header = {'content-type': 'application/json; charset=utf-8'}
request = requests.post(url,params=para,headers=header)
response = request.json()
# print(json.dumps(response,sort_keys=True,indent=2))
total = response['content']['page']['total']
pageSize = response['content']['page']['pageSize']
if total % 2 == 0:
pagesum = total / pageSize
else:
pagesum = (total + 1) / pageSize
while currentpage < pagesum:
para = {"size": 2,
"page": currentpage} # 是指当前页,只不过先要知道最后页
request1 = requests.post(url, params=para, headers=header)
response2 = request1.json()
# 遍历列表的数据
for value in response2['content']['data']:
if value['iamge']=='':
pass
else:
picture.append(value['iamge'])
namelist.append(value['userId'])
currentpage = currentpage + 1
x=0
# print(namelist)
dir_name = 'D:\python image'
for urllim in picture:
pic = namelist[x]
if not os.path.exists(dir_name):
os.makedirs(dir_name)
# print('yes')
urllib.request.urlretrieve(urllim,'D:\python image\%s.jpg' % pic)
# print('yes')
x+=1

477

被折叠的 条评论
为什么被折叠?



