大家在上网冲浪的时候,看到喜欢的图片都想要保存下来,有的时候可以直接右键图片另存为,但有的时候图片是无法下载的,甚至需要跳转到其他的网页去,非常麻烦。这篇文章教大家用Python下载图片,那么如何利用Python实现简单的图片下载?具体请看下文。 一、页面抓取 #coding=utf-8 import urllib def getHtml(url): page = urllib.urlopen(url) html = page.read() return html html = getHtml("https://tieba.baidu.com/p/5582243679") print html 页面数据抓取过程定义了getHtml()函数,其作用是给getHtml()传递一个网址,最终进行整个页面的下载。 二、页面数据筛选 import re import urllib def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) return imglist html = getHtml("https://tieba.baidu.com/p/5582243679") print getImg(html) 页面数据筛选中,定义了一个新的函数getImg(),该函数的功能是筛选出.jpg格式的图片地址。 三、图片下载 #coding=utf-8 import urllib import re def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'%s.jpg' % x) x+=1 html = getHtml("https://tieba.baidu.com/p/5582243679") print getImg(html) 通过for循环获得所有符合条件的图片网址,并采用urllib.urlretrieve()方法,将远程数据下载到本地,并重新命名! |
|
来自: 老男孩IT教育 > 《Python培训》