前言

上周电脑重装,换了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. 【ACM】杭电OJ 2018
  2. c语言程序设计第二章的答案,C语言程序设计第二章作业参考答案
  3. 历届冬奥会举办地与举办时间
  4. 联想拯救者Y7000P 2021H deepin v20.2.4设置双屏显示:切记要用集显,NAVIDA独显不生效
  5. 基于VMware vSphere 5 企业虚拟化部署之六:VMware Center管理ESXi和配置资源池
  6. windows--bat--%0无限执行当前bat脚本
  7. linq to entity 错误 1 错误 75: 类型 视图名称 的键部分 “主键的列名1”无效。该键的所有部分都必须不可以为 null。(转)...
  8. Linux安装mysql客户端
  9. 办公搜索利器UTOOLS-基于EVERYTHING的文件快速搜索软件
  10. 京东咚咚架构演进(IM通讯)
  11. 深入理解之border属性(第一期)
  12. 2021-2027全球与中国微机械角速率传感器市场现状及未来发展趋势
  13. PDF怎么拆分?有哪些免费的PDF拆分软件
  14. 苹果终于入伙 WebRTC,新一代移动 Web 应用爆发路上还有哪些坑?
  15. Scratch软件编程等级考试一级——20210911
  16. nginx反向代理实践:将某个指定的域名代理到指定的服务
  17. python版本回退
  18. 海南楼市充斥着传说 投机者必将自食其果
  19. LEDs状态灯任务(线程)设计(基于RTOS)
  20. C语言中静态变量的概念和用法

热门文章

  1. 中小企业一年中破产率_有此问题的企业中有60%在6个月内破产
  2. 边缘计算投资将何去何从?
  3. java 重点!反射机制学习
  4. 无法安装服务“VMware Authorization Service” ,请确保您有足够的权限安装系统,如何解决?
  5. git从远端仓库拉取代码, 切换其他分支(develop)注意点
  6. 知识付费平台 最新源码免费分享 全部可运营 亲测 在线付费 在线课堂 在线考试 在线收费 在线直播 统统满足你
  7. turtle实例6 生命游戏
  8. FPGA Xilinx 7系列高速收发器GTX通信
  9. 模型发生过拟合现象时,通常可以采取哪些方法避免或者缓解该问题?
  10. 博学笃志 追求卓越--献给研究生的12条忠告与建议--来源:《学位与研究生教育》2006年第三期