python解析网页内容,将抓取到的图片保存到本机。
# -*- coding=utf8 -*-
# @author:fw
from urllib import request #引用urllib模块
import re
baseurl=''
saveDir=''
#解析网址,将图片保存到本地
def execUrl(url,savepath):
global baseurl,saveDir
baseurl=url
saveDir=savepath
response=request.urlopen(url) #打开网址
page=response.read() #读取网址内容(读取结果为byte字节流)
page=page.decode('utf-8') #读取的结果转普通文本
imglist=getImgList(page)
saveImg(imglist)
#将网络图片保存到本机
def saveImg(imglist):
global baseurl,saveDir
x=0
for path in imglist:
print(path)
request.urlretrieve(path, saveDir+'%s.jpg' % x)
x+=1
#解析网页源码,返回所有图片
def getImgList(html):
reg1 = r'src="(.+?\.jpg)"'
pattern1=re.compile(reg1)
imglist1=pattern1.findall(html)
reg2= r'url\((.+?\.jpg)\)'
pattern2=re.compile(reg2)
imglist2=pattern2.findall(html)
imglist=list(set(imglist1+imglist2))
return imglist
execUrl('http://www.51aspx.com','D://ok//')