Python爬虫实现获取动态gif格式搞笑图片的方法示例


Posted in Python onDecember 24, 2018

本文实例讲述了Python爬虫实现获取动态gif格式搞笑图片的方法。分享给大家供大家参考,具体如下:

有时候看到一些喜欢的动图,如果一个个取保存挺麻烦,有的网站还不支持右键保存,因此使用python来获取动态图,就看看就很有意思了

本次爬取的网站是  居然搞笑网 http://www.zbjuran.com/dongtai/list_4_1.html

思路:

获取当前页面内容

查找页面中动图所代表的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))

结果如下:

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

最终就能够获得动态图了

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python两种遍历字典(dict)的方法比较
May 29 Python
Python兔子毒药问题实例分析
Mar 05 Python
Python中的赋值、浅拷贝、深拷贝介绍
Mar 09 Python
python在不同层级目录import模块的方法
Jan 31 Python
python3 pandas 读取MySQL数据和插入的实例
Apr 20 Python
Python 数据处理库 pandas进阶教程
Apr 21 Python
在CMD命令行中运行python脚本的方法
May 12 Python
Python实现的括号匹配判断功能示例
Aug 25 Python
Python一键安装全部依赖包的方法
Aug 12 Python
PyCharm中Matplotlib绘图不能显示UI效果的问题解决
Mar 12 Python
python多进程使用函数封装实例
May 02 Python
PyCharm2020.1.1与Python3.7.7的安装教程图文详解
Aug 07 Python
python 在屏幕上逐字显示一行字的实例
Dec 24 #Python
python之Flask实现简单登录功能的示例代码
Dec 24 #Python
python实现逐个读取txt字符并修改
Dec 24 #Python
Python判断一个list中是否包含另一个list全部元素的方法分析
Dec 24 #Python
python读取txt文件中特定位置字符的方法
Dec 24 #Python
python进行文件对比的方法
Dec 24 #Python
Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】
Dec 24 #Python
You might like
第九节--绑定
2006/11/16 PHP
php _autoload自动加载类与机制分析
2012/02/10 PHP
php实现文件编码批量转换
2014/03/10 PHP
Codeigniter校验ip地址的方法
2015/03/21 PHP
Nigma vs Alliance BO5 第二场2.14
2021/03/10 DOTA
浅析javascript中的DOM
2015/03/01 Javascript
jqGrid中文文档之选项设置
2015/12/02 Javascript
详细讲解JavaScript中的this绑定
2016/10/10 Javascript
基于JQuery的购物车添加删除以及结算功能示例
2017/03/08 Javascript
JS/jquery实现一个网页内同时调用多个倒计时的方法
2017/04/27 jQuery
Bootstrap提示框效果的实例代码
2017/07/12 Javascript
vue数组对象排序的实现代码
2018/06/20 Javascript
vue实现重置表单信息为空的方法
2018/09/29 Javascript
关于vue里页面的缓存详解
2019/11/04 Javascript
Javascript模拟实现new原理解析
2020/03/03 Javascript
vue的hash值原理也是table切换实例代码
2020/12/14 Vue.js
利用Python脚本在Nginx和uwsgi上部署MoinMoin的教程
2015/05/05 Python
Python实现在线音乐播放器
2017/03/03 Python
Python日期的加减等操作的示例
2017/08/15 Python
Python实现将照片变成卡通图片的方法【基于opencv】
2018/01/17 Python
深入理解Python异常处理的哲学
2019/02/01 Python
Django框架登录加上验证码校验实现验证功能示例
2019/05/23 Python
Python获取统计自己的qq群成员信息的方法
2019/11/15 Python
解决Python3.8用pip安装turtle-0.0.2出现错误问题
2020/02/11 Python
Django全局启用登陆验证login_required的方法
2020/06/02 Python
详解CSS3中的box-sizing(content-box与border-box)
2019/04/19 HTML / CSS
茵宝(Umbro)英国官方商店:英国足球服装生产商
2016/12/29 全球购物
出门问问全球官方商城:Tichome音箱和TicWatch智能手表
2017/12/02 全球购物
判断单链表中是否存在环
2012/07/16 面试题
如何找出EMP表里面SALARY第N高的employee
2013/12/05 面试题
工作过失检讨书
2014/02/23 职场文书
人事任命书怎么写
2014/06/05 职场文书
给妈妈洗脚活动方案
2014/08/16 职场文书
Python 如何实现文件自动去重
2021/06/02 Python
mysql定时自动备份数据库的方法步骤
2021/07/07 MySQL
MySQL创建管理RANGE分区
2022/04/13 MySQL