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解析json实例方法
Nov 19 Python
python实现定时同步本机与北京时间的方法
Mar 24 Python
Python中的urllib模块使用详解
Jul 07 Python
总结网络IO模型与select模型的Python实例讲解
Jun 27 Python
Python Django使用forms来实现评论功能
Aug 17 Python
python中学习K-Means和图片压缩
Nov 20 Python
Python获取CPU、内存使用率以及网络使用状态代码
Feb 08 Python
Python实现接受任意个数参数的函数方法
Apr 21 Python
python 获得任意路径下的文件及其根目录的方法
Feb 16 Python
Python3视频转字符动画的实例代码
Aug 29 Python
python之MSE、MAE、RMSE的使用
Feb 24 Python
python+opencv实现视频抽帧示例代码
Jun 11 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
php提交表单时判断 if($_POST[submit])与 if(isset($_POST[submit])) 的区别
2011/02/08 PHP
PHP安全防范技巧分享
2011/11/03 PHP
php检测文件编码的方法示例
2014/04/25 PHP
php单例模式实现方法分析
2015/03/14 PHP
PHP概率计算函数汇总
2015/09/13 PHP
PHP超全局变量实现原理及代码解析
2020/09/01 PHP
jquery之empty()与remove()区别说明
2010/09/10 Javascript
基于JQuery 的消息提示框效果代码
2011/07/31 Javascript
js 验证身份证信息有效性
2014/03/28 Javascript
借助JavaScript脚本判断浏览器Flash Player信息的方法
2014/07/09 Javascript
详解JavaScript中数组和字符串的lastIndexOf()方法使用
2016/03/13 Javascript
JavaScript必知必会(六) delete in instanceof
2016/06/08 Javascript
jQuery实现鼠标选中文字后弹出提示窗口效果【附demo源码】
2016/09/05 Javascript
深入理解javascript函数参数与闭包
2016/12/12 Javascript
javascript 跨域问题以及解决办法
2017/07/17 Javascript
vue打包之后生成一个配置文件修改接口的方法
2018/12/09 Javascript
vue项目前端知识点整理【收藏】
2019/05/13 Javascript
bootstrap-table+treegrid实现树形表格
2019/07/26 Javascript
vue 自动化路由实现代码
2019/09/03 Javascript
微信浏览器左上角返回按钮监听的实现
2020/03/04 Javascript
vue 实现一个简单的全局调用弹窗案例
2020/09/10 Javascript
解决antd Form 表单校验方法无响应的问题
2020/10/27 Javascript
利用信号如何监控Django模型对象字段值的变化详解
2017/11/27 Python
解决Mac安装scrapy失败的问题
2018/06/13 Python
Python 实现微信防撤回功能
2019/04/29 Python
Flask 上传自定义头像的实例详解
2020/01/09 Python
Django执行源生mysql语句实现过程解析
2020/11/12 Python
Too Faced官网:美国知名彩妆品牌
2017/03/07 全球购物
英国灯具和灯泡网上商店:Lights.co.uk
2018/02/02 全球购物
白俄罗斯女装和针织品网上商店:Presli.by
2019/10/13 全球购物
小小的船教学反思
2014/02/21 职场文书
宣传标语大全
2014/07/01 职场文书
篮球友谊赛通讯稿
2014/10/10 职场文书
2015年元旦主持词开场白
2014/12/14 职场文书
教研活动主持词
2015/07/03 职场文书
使用 CSS 轻松实现一些高频出现的奇形怪状按钮
2021/12/06 HTML / CSS