Python实现图片批量下载:从抓取到保存的完整教程
本文详细介绍如何使用Python编写简单的爬虫程序来批量下载网页图片。通过定义getHtml函数抓取页面源码,利用正则表达式筛选.jpg格式链接,并结合urllib.urlretrieve方法实现本地保存。文章还补充了urlopen与Request对象的使用差异,以及文件写入的两种常见写法,帮助初学者快速掌握图片抓取的核心技巧。
在日常网络浏览中,我们常需获取网络图片。若数量较少,通常可直接右键保存;但若图片受到特殊保护导致右键菜单无保存选项,或需批量处理大量图片时,手动操作将极为繁琐。此时,编写一段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()函数。该函数的主要功能是接收一个URL地址作为参数,执行下载操作,并返回整个页面的HTML源码。
二、页面数据筛选
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()函数,其核心逻辑是利用正则表达式从HTML文本中提取出所有以.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)
通过遍历筛选出的图片URL列表,利用urllib.urlretrieve()函数将远程图片数据流直接保存至本地磁盘,并根据需要为每张图片指定新的文件名。
以下是补充说明
具体示例如下所示:
import urllib.request
response = urllib.request.urlopen('https://www.jb51.net/g/500/600')
cat_img = response.read()
with open('cat_500_600.jpg','wb') as f:
f.write(cat_img)
urlopen()函数接收的参数既可以是字符串形式的URL,也可以是Request对象。当传入字符串时,urllib会自动将其转换为Request对象,因此以下两种写法在功能上等效。
response = urllib.request.urlopen('https://www.jb51.net/g/500/600')
req = urllib.request.Request('https://www.jb51.net/g/500/600')
1、使用Request对象调用urlopen:response = urllib.request.urlopen(req) 2、获取的response对象包含geturl()、info()和getcode()等方法,可用于获取URL、响应头及状态码。
代码片段: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()
以上即为Python实现图片下载的完整方法,内容简明易懂,供各位参考学习。若觉得有用,欢迎支持本站内容。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













