Python爬虫实战:批量抓取动态GIF图片的完整流程

Evan
Evan
发布时间:2026-10-13| 6人浏览过
原创

本文介绍利用Python编写爬虫程序,自动从指定网站批量抓取动态GIF图片的方法。通过解析HTML页面获取图片链接,并实现多页循环下载与本地存储,解决手动保存繁琐及部分网站禁止右键的问题。

本文详细介绍如何使用Python爬虫技术获取动态GIF格式的搞笑图片,并提供完整的实现示例,供读者参考学习。

在日常浏览中,若遇到喜欢的动图,手动逐一保存不仅耗时,且部分网站禁止右键保存。利用Python编写爬虫程序来自动获取这些动态图片,是一种高效且有趣的解决方案。

本示例选取的目标网站为居然搞笑网,具体页面链接为 http://www.zbjuran.com/dongtai/list_4_1.html。

实现思路如下:

第一步,获取目标页面的HTML内容。

第二步,解析页面结构,提取出所有动态图片对应的URL地址。

第三步,根据提取的URL下载图片数据,并将其保存至本地指定目录。

若需爬取多个页面的内容,只需在程序中加入循环逻辑即可实现批量处理。

具体代码实现如下:

#!/usr/bin/python
#coding:utf-8
import urllib2,time,uuid,urllib,os,sys,re
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf-8')
#获取页面内容
def getHtml(url):
    try:
        print url
        html = urllib2.urlopen(url).read()#.decode('utf-8')#解码为utf-8
    except:
        return
    return html
#获取动图所代表的url列表
def getImagUrl(html):
    if not html:
        print 'nothing can be found'
        return
    ImagUrlList=[]
    soup=BeautifulSoup(html,'lxml')
    #获取item列表
    items=soup.find("div",{"class":"main"}).find_all('div',{'class':'item'})
    for item in items:
        target={}
        #通过if语句,过滤广告项
        if item.find('div',{"class":"text"}):
            #获取url
            imgurl=item.find('div',{"class":"text"}).find('img').get('src')
            target['url']=imgurl
            #获取名字
            target['name']=item.find('h3').text
            ImagUrlList.append(target)
    return ImagUrlList
#下载图片到本地
def download(author,imgurl,typename,pageNo):
    #定义文件夹的名字
    x = time.localtime(time.time())
    foldername = str(x.__getattribute__("tm_year"))+"-"+str(x.__getattribute__("tm_mon"))+"-"+str(x.__getattribute__("tm_mday"))
    download_img=None
    picpath = 'Jimy/%s/%s/%s' % (foldername,typename,str(pageNo))
    filename = author+str(uuid.uuid1())
    pic_type=imgurl[-3:]
    if not os.path.exists(picpath):
        os.makedirs(picpath)
    target = picpath+"/%s.%s" % (filename,pic_type)
    print "动图存贮位置:"+target
    download_img = urllib.urlretrieve(imgurl, target)#将图片下载到指定路径中
    print "图片出处为:"+imgurl
    return download_img
#退出函数
def myquit():
    print "Bye Bye!"
    exit(0)
def start(pageNo):
    targeturl="http://www.zbjuran.com/dongtai/list_4_%s.html" % str(pageNo)
    html = getHtml(targeturl)
    urllist=getImagUrl(html)
    for imgurl in urllist:
        download(imgurl['name'],imgurl['url'],'搞笑动图',pageNo)
if __name__ == '__main__':
    print '''
            *****************************************
            **  Welcome to Spider of GIF     **
            **   Created on 2017-3-16      **
            **   @author: Jimy         **
            *****************************************'''
    pageNo = raw_input("Input the page number you want to scratch (1-50),please input 'quit' if you want to quit\n\
请输入要爬取的页面,范围为(1-100),如果退出,请输入Q>\n>")
    while not pageNo.isdigit() or int(pageNo) > 50 or int(pageNo) < 1:
        if pageNo == 'Q':
            myquit()
        print "Param is invalid , please try again."
        pageNo = raw_input("Input the page number you want to scratch >")
    print pageNo
    start(pageNo)
    #第一次爬取结束
    pageNo = raw_input("Input the page number you want to scratch (1-50),please input 'quit' if you want to quit\n\
请输入总共需要爬取的页面,范围为(1-5000),如果退出,请输入Q>\n>")
    while not pageNo.isdigit() or int(pageNo) > 5000 or int(pageNo) < 1:
        if pageNo == 'Q':
            myquit()
        print "Param is invalid , please try again."
        pageNo = raw_input("Input the page number you want to scratch >")
    #循环遍历,爬取多页
    for num in xrange(int(pageNo)):
        start(str(num+1))

程序运行后的输出结果示例如下:

*****************************************\n ** Welcome to Spider of GIF **\n ** Created on 2017-3-16 **\n ** @author: Jimy **\n *****************************************\nInput the page number you want to scratch (1-50),please input 'quit' if you want to quit\n请输入要爬取的页面,范围为(1-100),如果退出,请输入Q>\n>1\n1\nhttp://www.zbjuran.com/dongtai/list_4_1.html\n动图存贮位置:Jimy/2017-3-16/搞笑动图/1/真是艰难的选择。3f0fe8f6-09f8-11e7-9161-f8bc12753d1e.gif\n图片出处为:http://www.zbjuran.com/uploads/allimg/170206/10-1F206135ZHJ.gif\n动图存贮位置:Jimy/2017-3-16/搞笑动图/1/这么会被打死吧……3fa9da88-09f8-11e7-9161-f8bc12753d1e.gif\n图片出处为:http://www.zbjuran.com/uploads/allimg/170206/10-1F206135H35U.gif\n动图存贮位置:Jimy/2017-3-16/搞笑动图/1/一看就是印度……4064e60c-09f8-11e7-9161-f8bc12753d1e.gif\n图片出处为:http://www.zbjuran.com/uploads/allimg/170206/10-1F20613543c50.gif\n动图存贮位置:Jimy/2017-3-16/搞笑动图/1/新垣结衣的正经工作脸414b4f52-09f8-11e7-9161-f8bc12753d1e.gif\n图片出处为:http://www.zbjuran.com/uploads/allimg/170206/10-1F206135250553.gif\n动图存贮位置:Jimy/2017-3-16/搞笑动图/1/妹子这是在摇什么的421afa86-09f8-11e7-9161-f8bc12753d1e.gif\n图片出处为:http://www.zbjuran.com/uploads/allimg/170206/10-1F20613493N03.gif\nInput the page number you want to scratch (1-50),please input 'quit' if you want to quit\n请输入总共需要爬取的页面,范围为(1-5000),如果退出,请输入Q>\n>Q\nBye Bye!

通过上述流程,即可成功获取并保存所需的动态GIF图片。

如需进一步了解Python相关技术,可参考本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。

希望本文所述的实现方法能对您的Python编程实践有所帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。