PHP前端开发

python下载图片实现方法(超简单)

百变鹏仔 1个月前 (02-07) #Python
文章标签 下载图片

这篇文章介绍的内容是python下载图片实现方法(超简单),有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

下面小编就为大家带来一篇python下载图片实现方法(超简单)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

我们有时候会需要在网上查找并下载图片,当数量比较少的时候,点击右键保存,很轻松就可以实现图片的下载,但是有些图片进行了特殊设置,点击右键没有显示保存选项,或者需要下载很多图片,这样的情况,写一段Python爬虫代码就可以轻松解决!

一、页面抓取


#coding=utf-8import urllibdef getHtml(url):  page = urllib.urlopen(url)    html = page.read()    return htmlhtml = getHtml("https://tieba.baidu.com/p/5582243679")print html

页面数据抓取过程定义了getHtml()函数,其作用是给getHtml()传递一个网址,最终进行整个页面的下载。

立即学习“Python免费学习笔记(深入)”;

二、页面数据筛选


import reimport urllibdef getHtml(url):    page = urllib.urlopen(url)    html = page.read()    return htmldef getImg(html):    reg = r'src="(.+?.jpg)" pic_ext'    imgre = re.compile(reg)    imglist = re.findall(imgre,html)  return imglisthtml = getHtml("https://tieba.baidu.com/p/5582243679")print getImg(html)

页面数据筛选中,定义了一个新的函数getImg(),该函数的功能是筛选出.jpg格式的图片地址。

三、图片下载


#coding=utf-8import urllibimport redef getHtml(url):  page = urllib.urlopen(url)  html = page.read()    return htmldef 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+=1html = getHtml("https://tieba.baidu.com/p/5582243679")print getImg(html)

通过for循环获得所有符合条件的图片网址,并采用urllib.urlretrieve()方法,将远程数据下载到本地,并重新命名!

以下是补充

如下所示:


import urllib.requestresponse = urllib.request.urlopen('http://www.jb51.net/g/500/600')cat_img = response.read()with open('cat_500_600.jpg','wb') as f: f.write(cat_img)

urlopen()括号里既可以是一个字符串也可以是一个request对象,当传入字符串的时候会转换成一个request对象,因此代码

response = urllib.request.urlopen('http://www.jb51.net/g/500/600') 也可以写成

req = urllib.request.Request('http://www.jb51.net/g/500/600')

1、response = urllib.request.urlopen(req)
2、responce还有geturl,info,getcode方法

代码with open('cat_500_600.jpg','wb') as f:

f.write(cat_img)等价于

1、f = open('cat_500_600.jpg','wb')

2、try:

3、 data = f.write(cat_img)

4、finally:

5、 f.close()