如何利用 Python 实现简单图片下载功能
我们有时候会需要在网上查找并下载图片,当数量比较少的时候,点击右键
保存,很轻松就可以实现图片的下载,但是有些图片进行了特殊设置,点击右键
没有显示保存选项,或者需要下载很多图片,这样的情况,写一段Python爬虫
代码就可以轻松解决!
一、页面抓取
#coding=utf-8
importurllib
defgetHtml(url):
page=urllib.urlopen(url)
html=page.read()
returnhtml
html=getHtml("https://tieba.baidu.com/p/5582243679")
printhtml
页面数据抓取过程定义了getHtml()函数,其作用是给getHtml()传递一个
网址,最终进行整个页面的下载。
二、页面数据筛选
importre
importurllib
defgetHtml(url):
page=urllib.urlopen(url)html=page.read()
returnhtml
defgetImg(html):
reg=r'src="(.+?\.jpg)"pic_ext'
imgre=re.compile(reg)
imglist=re.findall(imgre,html)
returnimglist
html=getHtml("https://tieba.baidu.com/p/5582243679")
printgetImg(html)
页面数据筛选中,定义了一个新的函数getImg(),该函数的功能是筛选
出.jpg格式的图片地址。
三、图片下载
#coding=utf-8
importurllib
importre
defgetHtml(url):
page=urllib.urlopen(url)
html=page.read()
returnhtml
defgetImg(html):
reg=r'src="(.+?\.jpg)"pic_ext'
imgre=re.compile(reg)imglist=re.findall(imgre,html)
x=0
forimgurlinimglist:
urllib.urlretrieve(imgurl,'%s.jpg'%x)
x+=1
html=getHtml("https://tieba.baidu.com/p/5582243679")
printgetImg(html)
通过for循环获得所有符合条件的图片网址,并采用urllib.urlretrieve()
方法,将远程数据下载到本地,并重新命名!
以上内容为大家介绍了如何利用Python实现简单图片下载功能,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

相关推荐HOT
更多>>
pythonfor循环是什么
pythonfor循环是什么在做遍历的时候,对于一些数据的反复循环执行,我们会用到for循环的语句。可以说这是新手入门必学的语句之一,在很多基础循...详情>>
2023-11-13 07:46:36
pythoncontextmanager()的转换
python中contextmanager()的转换1、说明当发出请求时,requests库会在将请求实际发送到目标服务器之前准备该请求。请求准备包括像验证头信息和...详情>>
2023-11-13 06:34:35
python使用items()遍历键值对
python使用items()遍历键值对字典可以用来存储各种方式的信息,所以有很多方式可以通过字典的所有键值对、键或值。说明1、即使通过字典,键值对...详情>>
2023-11-13 04:24:15
python实例方法中self的作用
python实例方法中self的作用说明1、无论是创建类的构造方法还是实例方法,最少要包含一个参数self。2、通过实例的self参数与对象进行绑定,程序...详情>>
2023-11-13 03:46:48