编写Python脚本批量下载DesktopNexus壁纸的教程


Posted in Python onMay 06, 2015

DesktopNexus 是我最喜爱的一个壁纸下载网站,上面有许多高质量的壁纸,几乎每天必上, 每月也必会坚持分享我这个月来收集的壁纸

但是 DesktopNexus 壁纸的下载很麻烦,而且因为壁纸会通过浏览器检测你当前分辨率来展示 合适你当前分辨率的壁纸,再加上是国外的网站,速度上很不乐观。

于是我写了个脚本,检测输入的页面中壁纸页面的链接,然后批量下载到指定文件夹中。

脚本使用 python 写的,所以需要机器上安装有 python 。
用法:

$ python desktop_nexus.py -p http://www.desktopnexus.com/tag/cat/ -s 1280x800 -o wallpapers

    -p 包含 DesktopNexus 壁纸链接的页面,比如我的壁纸分享
    -s 壁纸尺寸,可选,缺省为 1440x900
    -o 壁纸输出的文件夹,可选,缺省为当前目录下的 wallpapers, 如果不存在会自动创建

代码:

#-*- coding: utf-8 -*-
from argparse import ArgumentParser

import os, re, sys
import urllib2, cookielib, urlparse

RE_WALLPAPER = r'http\:\/\/[^\/\.]+\.desktopnexus\.com\/wallpaper\/\d+\/'
CHUNK_SIZE = 1024 * 3

class DesktopNexus:
  def __init__(self, page=None, size=None, output_dir=None):
    self.page = page
    self.size = size
    self.output_dir = output_dir

  def start(self):
    print 'Making output directory:', self.output_dir
    if not os.path.exists(self.output_dir):
      os.makedirs(self.output_dir)

    # Setup cookie
    cookie = cookielib.CookieJar()
    processer = urllib2.HTTPCookieProcessor(cookie)
    opener = urllib2.build_opener(processer)
    urllib2.install_opener(opener)

    self._read_page()

  def _get_pic_info(self, url):
    pic_id = url.split('/')[-2]
    html = urllib2.urlopen(url).read()
    pattern = r'<a href=\"\/get\/%s\/\?t=(?P<token>.*?)\"' % pic_id
    match = re.search(pattern, html, flags=re.I|re.M|re.S)
    if match:
      return {'id': pic_id,
          'token': match.group('token'),
          'size': self.size}
    else:
      raise Exception('Cound not find wallpaper')

  def _get_pic_file(self, pic_info):
    redirect_url = 'http://www.desktopnexus.com/dl/inline/%(id)s/%(size)s/%(token)s' % pic_info

    request = urllib2.urlopen(redirect_url)
    return request.geturl()

  def _download_pic(self, url):
    pic_info = self._get_pic_info(url)
    pic_file = self._get_pic_file(pic_info)
    filename = os.path.split(urlparse.urlparse(pic_file).path)[-1]
    filename = os.path.join(self.output_dir, filename)
    with open(filename, 'wb') as output:
      resp = urllib2.urlopen(pic_file)
      total_size = int(resp.info().get('Content-Length'))
      saved_size = 0.0
      while saved_size != total_size:
        chunk = resp.read(CHUNK_SIZE)
        saved_size += len(chunk)
        output.write(chunk)
        self._print_progress('Saving file: %s' % filename, \
            saved_size / total_size * 100)

  def _print_progress(self, msg, progress):
    sys.stdout.write('%-71s%3d%%\r' \
        % (len(msg) <= 70 and msg or msg[:67] + '...', progress))
    sys.stdout.flush()
    if progress >= 100:
      sys.stdout.write('\n')

  def _read_page(self):
    try:
      print 'Fetching content:', self.page
      html = urllib2.urlopen(self.page).read()
      links = set(re.findall(RE_WALLPAPER, html, re.M|re.I))
      count = len(links)

      print 'Downloading wallpapers:'
      for i, link in enumerate(links):
        print '[%d/%d]: %s' % (i + 1, count, link)
        try:
          self._download_pic(link)
        except Exception as e:
          print 'Error downloading wallpaper.', e.message
    except Exception as e:
      print 'Error fetching content.', e

if __name__ == '__main__':
  # Setup argparser
  parser = ArgumentParser('python desktop_nexus.py')
  parser.add_argument('-p', '--page', dest='page', required=True, \
      help='specific a page that includes wallpaper list')
  parser.add_argument('-s', '--size', dest='size', default='1440x900', \
      help='specific the wallpaper size, default to 1440x900')
  parser.add_argument('-o', '--output', dest='output_dir', default='wallpapers', \
      help='specific the output directory, default to "wallpapers"')
  args = parser.parse_args()
  dn = DesktopNexus(**args.__dict__)
  dn.start()

Python 相关文章推荐
python用字典统计单词或汉字词个数示例
Apr 22 Python
简单的连接MySQL与Python的Bottle框架的方法
Apr 30 Python
python删除特定文件的方法
Jul 30 Python
使用Python发送各种形式的邮件的方法汇总
Nov 09 Python
用python处理图片之打开\显示\保存图像的方法
May 04 Python
python 读取Linux服务器上的文件方法
Dec 27 Python
使用Python正则表达式操作文本数据的方法
May 14 Python
Django中URL的参数传递的实现
Aug 04 Python
Django app配置多个数据库代码实例
Dec 17 Python
np.dot()函数的用法详解
Jan 17 Python
pycharm2020.2 配置使用的方法详解
Sep 16 Python
python 如何使用find和find_all爬虫、找文本的实现
Oct 16 Python
在Windows服务器下用Apache和mod_wsgi配置Python应用的教程
May 06 #Python
利用Python脚本在Nginx和uwsgi上部署MoinMoin的教程
May 05 #Python
Python实现的HTTP并发测试完整示例
Apr 23 #Python
安装dbus-python的简要教程
May 05 #Python
使用SAE部署Python运行环境的教程
May 05 #Python
在Python中使用PIL模块对图片进行高斯模糊处理的教程
May 05 #Python
在Python中使用mechanize模块模拟浏览器功能
May 05 #Python
You might like
php的计数器程序
2006/10/09 PHP
C# Assembly类访问程序集信息
2009/06/13 PHP
用按钮控制iframe显示的网页实现方法
2013/02/04 Javascript
微信小程序 PHP生成带参数二维码
2017/02/21 Javascript
JS实现的四级密码强度检测功能示例
2017/05/11 Javascript
Nodejs 和Session 原理及实战技巧小结
2017/08/25 NodeJs
javascript将list转换成树状结构的实例
2017/09/08 Javascript
浅谈React高阶组件
2018/03/28 Javascript
Vue 与 Vuex 的第一次接触遇到的坑
2018/08/16 Javascript
jQuery 操作 HTML 元素和属性的方法
2018/11/12 jQuery
vue实现PC端录音功能的实例代码
2019/06/05 Javascript
微信小程序中悬浮窗功能的实现代码
2019/08/02 Javascript
JavaScript字符串处理常见操作方法小结
2019/11/15 Javascript
Js逆向实现滑动验证码图片还原的示例代码
2020/03/10 Javascript
基于vue+element实现全局loading过程详解
2020/07/10 Javascript
[14:51]DOTA2 HEROS教学视频教你分分钟做大人-卓尔游侠
2014/06/13 DOTA
[01:00:54]TI4正赛第二日开场
2014/07/20 DOTA
[02:37]2018DOTA2亚洲邀请赛赛前采访 VP.no[o]ne心中最强SOLO是谁
2018/04/04 DOTA
python算法学习之计数排序实例
2013/12/18 Python
Python连接SQLServer2000的方法详解
2017/04/19 Python
python中类变量与成员变量的使用注意点总结
2017/04/29 Python
python在ubuntu中的几种安装方法(小结)
2017/12/08 Python
python自定义函数实现最大值的输出方法
2019/07/09 Python
利用Python实现Shp格式向GeoJSON的转换方法
2019/07/09 Python
Python单元测试工具doctest和unittest使用解析
2019/09/02 Python
python之语音识别speech模块
2020/09/09 Python
CSS3的column-fill属性对齐列内容高度的用法详解
2016/07/01 HTML / CSS
经济实惠的豪华家具:My-Furniture
2019/03/12 全球购物
自荐信格式技巧有哪些呢
2013/11/19 职场文书
竞争性谈判邀请书
2014/02/06 职场文书
2015年公务员工作总结
2015/04/24 职场文书
男人帮观后感
2015/06/18 职场文书
小学毕业感言200字
2015/07/30 职场文书
党员观看《筑梦中国》心得体会
2016/01/18 职场文书
python代码实现扫码关注公众号登录的实战
2021/11/01 Python
解决persistence.xml配置文件修改存放路径的问题
2022/02/24 Java/Android