python web-spider之图片保存

来源:互联网 发布:unity3d 披风插件 编辑:程序博客网 时间:2024/05/29 11:03

为了更好的展示爬取的目标网站内容,下载目标网站所使用的图片是有必要的。

保持图片在目标网站中的相对路径和名称是比较合适的方案,这需要对图片URL进行split处理。

创建相对路径的代码如下:

def createPath(url):folders=url.split('/')i=3path=folders[2]while i<len(folders)-1:path=os.path.join(path,folders[i])i+=1if not os.path.exists(path):os.makedirs(path)path=path+"/"return path

从图片URL中获取文件名称:

filename=imgurl.split('/')[-1]

以下代码可以获取页面中的所有jpg图片,并保存到当前目录下与目标网站相一致的相对路径中。

import reimport urllibimport os def getHtml(url):page = urllib.urlopen(url)html = page.read()return htmldef createPath(url):folders=url.split('/')i=3path=folders[2]while i<len(folders)-1:path=os.path.join(path,folders[i])i+=1if not os.path.exists(path):os.makedirs(path)path=path+"/"return pathdef getImg(html):reg = r'src="?\'?(\S+\.jpg)"?\'?'imgre = re.compile(reg)imglist = imgre.findall(html)x = 0for imgurl in imglist:if not re.match("^http",imgurl):imgurl="http://image.baidu.com/"+imgurl    print imgurlfilename=imgurl.split('/')[-1]path=createPath(imgurl)filename=path+filenameprint filenameurllib.urlretrieve(imgurl,filename)html = getHtml("http://image.baidu.com")getImg(html)

上述代码会爬取image.baidu.com首页中所有的jpg图片,大部分图片并不在image.baidu.com这个服务器上,例如:http://img0.bdstatic.com/img/image/shouye/fslsdkdk.jpg,

这时代码会自动创建一个域名文件夹img0.bdstatic.com,然后在给文件夹下创建路径img/image/shouye/,最后下载文件fslsdkdk.jpg到img0.bdstatic.com/img/image/shouye/路径下。

参考

http://www.oschina.net/question/1016509_114210

0 0
原创粉丝点击