前言

上周电脑重装,换了ubuntu 16.04,想起来之前上课老师也是ubuntu而且他还提到他桌面是他自己写的个小脚本实现的自动更换桌面壁纸的,昨天晚上心血来潮自己网上搜了点资料实现了一下 = =

功能

功能的话,是从必应壁纸爬取最新的那张壁纸,然后本来因为我怕电脑又放了太多东西,就设置了个图片最大的数目,到达这个阈值就删除所有的图片= =|| 通过python的os模块,设置壁纸,这里可以参考:how-to-change-desktop-background-from-command-line-in-unity , 还有就是考虑到刚开机时我不一定连得上网(辛酸 T_T),所以设置了一个爬取的间隔


Release1.0 代码

# -*- coding: utf-8 -*-
#!/usr/bin/python
#!/bin/bash# ---------------------------------------------------------- #
# This is a script which can change background automatically #
# every time the system starts.                               #
# author: Huang Zhenyang                                     #
# email: 745125931@qq.com                                    #
# ---------------------------------------------------------- ## ----- Import ----- #
import os
import re
import urllib
import time
import socket
# --- End Import --- #class Spider(object):"""This is the spider to get the img from being"""def __init__( self, img_matched_pattern_para, url_para, file_name_para ):"""init function:param img_matched_pattern_para: the pattern to match a img:param url_para: url to crawler:param file_name_para: file name"""self.img_matched_pattern = img_matched_pattern_paraself.url = url_paraself.file_name = file_name_paradef get_img(self):"""download the image:return:"""html = self.get_html()img_pos = re.search(self.img_matched_pattern, html)img_page_href = self.url + img_pos.group()[6:-7] + "download"urllib.urlretrieve(img_page_href, self.file_name)def get_html(self):"""return the html:return: page's html <type 'str'>"""page = urllib.urlopen(self.url)html = page.read()return htmlclass Controller(object):"""This is the controller to control the spider's parameters."""def __init__(self, pattern_href_para, path_para, url_para, img_max_num_para):""":param pattern_href_para: href's match pattern:param path_para: path to save images:param url_para: url:param img_max_num_para: max number that the"""self.pattern_href = pattern_href_paraself.path = path_paraself.url = url_paraself.img_max_num = img_max_num_paraself.file_name = ""self.init_file_name = "0.jpg"self.file_extension_name = ".jpg"def judge(self):"""judge if the number of images is grater than img_max_num.if true, delete all of them and then run spider, else directly run spider.Also, we should set the file name.:return:"""root = None_dirs = Nonefiles = Nonefor root, _dirs, files in os.walk(self.path, True):passfiles_len = len(files)if files_len == 10:for i in range(0, 10):os.remove(root + files[i])self.file_name = self.path + self.init_file_nameelse:self.file_name = self.path + str(files_len) + self.file_extension_namedef run_spider(self):"""run spider.TODO: This function needs to be modified in the future which makes these two class coupling too much.:return:"""# In case user's computer hasn't connect the internet.for i in range(0, 60):try:spider = Spider(self.pattern_href, self.url, self.file_name)spider.get_img()breakexcept IOError as e:print "Connection error: %s" % etime.sleep(60)continueexcept Exception as e:print "Connection error: %s" % etime.sleep(60)continuec_path = '"file://' + self.file_name + '"'  # absolute path# call system command to change the gnome backgroundos.system('gsettings set org.gnome.desktop.background picture-uri ' + c_path)print "gsettings set org.gnome.desktop.background picture-uri " + c_pathif __name__ == '__main__':pattern_href = r'href="/photo/.*?"'path = '/home/hzy/图片/backgrounds/'url = 'https://bing.ioliu.cn/'img_max_num = 10controller = Controller(pattern_href, path, url, img_max_num)controller.judge()controller.run_spider()

开机自启动

/home/hzy/.config/autostart中,新建一个xxx.desktop的文件,内容如下:

[Desktop Entry]
Name=autoChangeBackgroundImg
Comment=Python Program
Exec=python /home/hzy/Script/autoChangeBackgroundImg/autoChangeBackgroundImg.py
Icon=/home/hzy/Script/autoChangeBackgroundImg/autoChangeBackgroundImg.png
Terminal=false
MultipleArgs=false
Type=Application
Categories=Application;Development;
StartupNotify=true

说明:

  1. Exec 后面的路径就是该脚本的路径
  2. Icon的话可以自己随便找个图片,设置成该路径即可

Release1.1 代码

更新说明

  1. 1.0的代码已经无法使用,必应高清壁纸和之前不太一样了,图片的下载链接不再能通过原来的方式获取
  2. 原来使用的urllib.urlretrieve()方法得到的不是图片,而是图片所在网页的整个html,改用urllib2.urlopen()方法获取
  3. 思路是先从必应高清壁纸中得到最新的图片的具体页面链接,再到该页面中匹配出图片的具体url。需要注意的是,图片具体页面中显示的图片url可以匹配的字段为class="mark"

    但是实际请求到的html中,class="mark"后面并没有图片的链接:

    接着寻找,找到了字段:data-progressive=

代码如下,只改了spider.get_img()方法的内容:

# -*- coding: utf-8 -*-
#!/usr/bin/python
#!/bin/bash# ---------------------------------------------------------- #
# This is a script which can change background automatically #
# every time the system start.                               #
# author: Huang Zhenyang                                     #
# email: 745125931@qq.com                                    #
# ---------------------------------------------------------- ## ----- Import ----- #
import os
import re
import urllib
import urllib2
import time
import socket
# --- End Import --- #class Spider(object):"""This is the spider to get the img from being"""def __init__( self, img_matched_pattern_para, url_para, file_name_para ):"""init function:param img_matched_pattern_para: the pattern to match a img:param url_para: url to crawler:param file_name_para: file name"""self.img_matched_pattern = img_matched_pattern_paraself.url = url_paraself.file_name = file_name_paradef get_img(self):"""download the image:return:"""html = self.get_html()img_pos = re.findall(self.img_matched_pattern, html)img_href_arr = []for each in img_pos:if 'th?id=' not in each:img_href_arr.append(each)img_page_href = self.url + img_href_arr[0][6:]# print("img_page_href: ", img_page_href)img_url_pattern = 'data-progressive="(.*?jpg)"'img_page_html = urllib.urlopen(img_page_href).read()# print("img_page_html: ", img_page_html)img_url = re.findall(img_url_pattern, img_page_html)[0]# print("img_url: ", img_url)header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) \AppleWebKit/537.36 (KHTML, like Gecko) \Chrome/35.0.1916.114 Safari/537.36','Cookie': 'AspxAutoDetectCookieSupport=1'}request = urllib2.Request(img_url, None, header)response = urllib2.urlopen(request)with open(self.file_name, "wb") as f:f.write(response.read())def get_html(self):"""return the html:return: page's html <type 'str'>"""page = urllib.urlopen(self.url)html = page.read()return htmlclass Controller(object):"""This is the controller to control the spider's parameters."""def __init__(self, pattern_href_para, path_para, url_para, img_max_num_para):""":param pattern_href_para: href's match pattern:param path_para: path to save images:param url_para: url:param img_max_num_para: max number that the"""self.pattern_href = pattern_href_paraself.path = path_paraself.url = url_paraself.img_max_num = img_max_num_paraself.file_name = ""self.init_file_name = "0.jpg"self.file_extension_name = ".jpg"def judge(self):"""judge if the number of images is grater than img_max_num.if true, delete all of them and then run spider, else directly run spider.Also, we should set the file name.:return:"""root = None_dirs = Nonefiles = Nonefor root, _dirs, files in os.walk(self.path, True):passfiles_len = len(files)if files_len == 10:for i in range(0, 10):os.remove(root + files[i])self.file_name = self.path + self.init_file_nameelse:self.file_name = self.path + str(files_len) + self.file_extension_namedef run_spider(self):"""run spider.TODO: This function needs to be modified in the future which makes these two class coupling too much.:return:"""spider = Spider(self.pattern_href, self.url, self.file_name)# In case user's computer hasn't connect the internet.for i in range(0, 60):try:spider.get_img()breakexcept IOError as e:print "Connection error: %s" % etime.sleep(60)continueexcept Exception as e:print "Connection error: %s" % etime.sleep(60)continuec_path = '"file://' + self.file_name + '"'  # absolute path# call system command to change the gnome backgroundos.system('gsettings set org.gnome.desktop.background picture-uri ' + c_path)print "gsettings set org.gnome.desktop.background picture-uri " + c_pathif __name__ == '__main__':pattern_href = r'href="/photo/.*?"'path = '/home/huangzhenyang/图片/backgrounds/'url = 'https://bing.ioliu.cn'img_max_num = 10controller = Controller(pattern_href, path, url, img_max_num)controller.judge()controller.run_spider()

ubuntu 16.04LTS 开机启动自动更换壁纸相关推荐

  1. ubuntu进入桌面自动启动脚本_ubuntu 16.04LTS 开机启动自动更换壁纸的实现方法

    前言 上周电脑重装,换了ubuntu 16.04,想起来之前上课老师也是ubuntu而且他还提到他桌面是他自己写的个小脚本实现的自动更换桌面壁纸的,昨天晚上心血来潮自己网上搜了点资料实现了一下 = = ...

  2. 让 Ubuntu 桌面自动更换壁纸

    让 Ubuntu 桌面自动更换壁纸 Posted on 2016-07-10 22:56 京山游侠 阅读(4256) 评论(10) 编辑 收藏 引言 让我们的桌面系统自动更换壁纸是一个很常见的美化需求 ...

  3. Ubuntu 14.04自动更换壁纸

    Ubuntu 14.04自动更换壁纸 最近用ubuntu14.04,想添加一些自己拍的图片作为壁纸,并且让它自动更换. 查网上教程,知道其实背景图片是在文件夹/usr/share/background ...

  4. service实现自动更换壁纸

    在activity中用以下代码使用 Intent intent = new Intent(MyActivity.this, ChangeService.class); startService(int ...

  5. android 通过service 执行AlarmManager 自动更换壁纸

    自动更换壁纸是通过服务在后台进行的,所以 新建一个类继承service服务 先附上详细的解析代码: package com.example.changebz; import java.io.IOExc ...

  6. linux学习之路——ubuntu 16.04 开机开启数字小键盘解决方法

    linux学习之路--ubuntu 16.04 开机开启数字小键盘解决方法 参考文章: (1)linux学习之路--ubuntu 16.04 开机开启数字小键盘解决方法 (2)https://www. ...

  7. Ubuntu下添加开机启动脚本

    [转载]Ubuntu下添加开机启动脚本 原文地址:http://blog.163.com/yangshuai126%40126/blog/static/173426265201092810164155 ...

  8. android 自动更换壁纸,安卓壁纸如何设置自动更换壁纸-手机天堂

    安卓壁纸是一款非常实用的手机壁纸更换软件,平台中有非常丰富的静态壁纸和视频动态壁纸,可以说是每天换一张都不会重样的,这就让手机变的更加的丰富多彩.相信有不少的朋友会认为老使用一张壁纸太单调,每天都换成 ...

  9. Ubuntu下添加开机启动项的2种方法

    Ubuntu下添加开机启动项的方法 1.方法一,编辑rc.loacl脚本 Ubuntu开机之后会执行/etc/rc.local文件中的脚本, 所以我们可以直接在/etc/rc.local中添加启动脚本 ...

最新文章

  1. 二十三、死锁的处理策略---避免死锁(银行家算法)
  2. 安卓开发20:动画之Animation 详细使用-主要通过java代码实现动画效果
  3. Pycharm 导入 Python 包、模块
  4. 专访4秒源码商城CTO陈杰:扎根互联网的“不安的心”
  5. POJ1328-Radar Installation
  6. frameset 后台管理_易达CMS下载-易达CMS(免费开源网站管理系统)v3.0.0.1103免费版
  7. swift 3.0 中使用 xib
  8. 虚拟机linux和主机网络连接,linux虚拟机中和主机三种网络连接方式的区别
  9. TTU智能配电终端_智能配电终端规模化建设及应用
  10. 两组的数据平均值合并_地理信息系统导论学习笔记(10)—数据探查
  11. python难学吗-Python入门很难吗? 为什么越来越多的人都学Python?
  12. 汉源高科2个万兆光24千兆网口万兆机架式工业交换机支持G.8032(ERPS)标准的以太环网交换机
  13. 人工智能课程设计——植物识别专家系统
  14. date设置时间提示:Local time zone must be set--see zic manual page 2018
  15. [leetcode 913] 猫和老鼠(博弈、dp)
  16. 百度地图画出手机GPS行驶轨迹——Web端
  17. (Tekla Structures二次开发)自动标注尺寸展示
  18. 基于验证分离的PLC保护系统
  19. sqlmap帮助文档(配合实践翻译)
  20. FRAM铁电存储器FM25W256编程实现存取数据

热门文章

  1. 三星Galaxy Note20 Ultra手机UWB芯片信息
  2. Android变相拦截Home键,使app一直运行在前端
  3. 当file_get_contents或者simplexml_load_file的时候乱码
  4. echart水滴_漂亮得不像实力派:ECharts 水球图教程
  5. 管理是什么——浅谈开发经理的管理
  6. 视频教程-大数据分析师实战课-大数据
  7. 减少过拟合(高方差)的方法
  8. bruce eckel.thinking in java_bruce eckel.thinking in java - 百度学术
  9. 有确定项微分方程的matlab程序,微分方程的数值解法matlab四阶龙格—库塔法课件...
  10. Windows8和MacOS10.9双系统安装及Mac经常使用软件安装--联想E49A