python 实现桌面壁纸自动更换
2017-07-25 16:56
639 查看
学了python大概两周了,今天做了个小程序,感觉还比较实用。在此记录一下
程序介绍
功能介绍:每隔30分钟,随机更换桌面。桌面资源是在zol网,自动爬取的热门图片开机自启设置:发送changeBg.exe快捷方式到 C:\用户\用户名\AppData\Roaming\Microsoft\Windows\「开始」菜单\程序\启动文件夹如果遇到不喜欢的图片,想要立即更换,则需要先杀死程序,再重新启动。程序每次启动时,都会立即更换一张背景图。关闭程序:本程序是后台程序,不提供用户界面。所以关闭需要打开任务管理器,在任务管理器中找到changeBg的任务,并结束。人生就像这个壁纸小程序,你永远也不知道下一张的壁纸长什么样。无意间的才叫惊喜程序大致思路 :爬取zol网上的热门图片链接,并存到数据库。每隔三十分钟获取图片链接,下载图片并设置背景图片。刚开始学python,类的运用还不时很熟练,所以用文件的形式来编写main 文件 负责各个模块的调用,主要逻辑import getBgUrls import fileUtils import threading import SetBg import random import db import time def setBgUrl(): #睡五秒钟,等待另一个线程爬取图片utl 这样可以运行程序,立即更换桌面 time.sleep(5) print('setBgUrl has executed') pic_urls = getBgUrls.pic_urls if len(pic_urls) > 0: abs_path = fileUtils.save_file(random.choice(pic_urls)) SetBg.set_wallpaper(abs_path) #每小时换一次 threading.Timer(60*30,setBgUrl).start() if __name__ == '__main__': times = db.getStartTimes() #第一次使用本程序 调用存储到数据库的爬虫 if times == 0 : t1 = threading.Thread(target=getBgUrls.get_pic_urls_to_db).start() elif times <= 10: #如果数据库的数据url长度为0,证明中途被打断,没有插入成功,需要重新开始 urls = db.getUrls() if len(urls) == 0: t1 = threading.Thread(target=getBgUrls.get_pic_urls_to_db).start() else: # 从数据库获取url getBgUrls.pic_urls = urls else : db.removeDb() fileUtils.removeAllPic() t1 = threading.Thread(target=getBgUrls.get_pic_urls_to_db).start() setBgUrl()
db文件,负责数据库的操作。数据库用的是python自带的sqlite,还挺好用的
import sqlite3import osprint('db has import')#程序每使用十次,就重新爬取数据file_path = r'D:\deskPicc'if not os.path.exists(file_path): os.mkdir(file_path)conn_main = sqlite3.connect(r'D:\deskPicc\background.db')cursor = conn_main.execute(r'SELECT count(*) FROM sqlite_master WHERE type="table" AND name="t_config"')for i in cursor: if i[0] == 0: #第一次运行程序,创建数据库config表,urls表 conn_main.execute(r'create table t_config(start_times int)') conn_main.execute(r"insert into t_config('start_times') values(0)") #初始化为0 conn_main.execute(r'create table t_urls(url varchar(200))') conn_main.commit()conn_main.close()# 拿到数据库链接,因为规定数据库链接和操作必须在统一线程def getConnection(): conn = sqlite3.connect(r'D:\deskPicc\background.db') return conn#返回程序使用的次数def getStartTimes(): conn = getConnection() cursor = conn.execute(r"select * from t_config") for i in cursor: times = i[0] times = int(times) + 1 sql = "update t_config set start_times = {}".format(str(times)) print(sql) conn.execute(sql) conn.commit() conn.close() return times - 1#插入url数据def insertInto(urls): conn = getConnection() for i in urls: sql = "insert into t_urls('url') values('{}')".format(i) conn.execute(sql) conn.commit() print(sql) conn.close()def getUrls(): conn = getConnection() sql = 'select * from t_urls' cursor = conn.execute(sql) urls = [i[0] for i in cursor] print('getUrls from db : ') print(urls) conn.commit() conn.close() return urlsdef removeDb(): conn = getConnection() sql1 = 'drop table t_config' sql2 = 'drop table t_urls' conn.execute(sql1) conn.execute(sql2) conn.commit() conn.close()getBgUrls文件主要负责解析网站,获取图片链接的url
import Httpfrom win32api import GetSystemMetricsimport dbpic_urls = [] # 存储所有的图片url#解析网站,获取图片urldef get_pic_urls_to_db():global pic_urlsbase_url = r'http://desk.zol.com.cn'hot_url = r'http://desk.zol.com.cn/pc/hot_1.html' #所有,按下载量排序#系统分辨率width = GetSystemMetrics(0)height = GetSystemMetrics(1)width_height = str(width)+'x'+str(height)soup = Http.visitUrl(hot_url)for i in soup.select(r'li.photo-list-padding > a'):url = base_url + i.get('href')soup = Http.visitUrl(url)for tag_a in soup.select(r'#showImg > li > a'):# 找到适合自己电脑分辨率的图片链接soup = Http.visitUrl(base_url + tag_a.get('href'))for i in soup.select('#tagfbl > a'):if width_height in i.get('href'):image_html = base_url + i.get('href')#print('image_html : ',image_html)soup = Http.visitUrl(image_html)tag_imgs = soup.select('body > img')if len(tag_imgs) > 0:pic_urls.append(tag_imgs[0].get('src'))print('has get image url',tag_imgs[0].get('src'))db.insertInto(pic_urls)fileUtils文件提供把图片保存到本地的方法
import Httpimport osfile_path = r'D:\deskPicc'file_pathes = []def save_file(url):if not os.path.exists(file_path):os.mkdir(file_path)os.chdir(file_path)response = Http.visitUrl_response(url)content = response.content#截取urlfile_name = url.split(r'/')[-1]with open(file_name,'wb') as f:if not os.path.exists(r'/'+file_name):f.write(content)abs_path = file_path+'\\'+ file_namefile_pathes.append(abs_path)print(abs_path,'has saved as a file')return abs_pathelse:print(file_name,'hax exist')def removeAllPic():for i in os.listdir(file_path):if 'background.db' in i:continueelse :abs_path = file_path + '\\' + iprint('remove : ', abs_path)os.remove(abs_path)setBg文件提供设置桌面背景的方法
import win32api, win32con, win32guidef set_wallpaper(img_path):# 打开指定注册表路径reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)# 最后的参数:2拉伸,0居中,6适应,10填充,0平铺win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")# 最后的参数:1表示平铺,拉伸居中等都是0win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")# 刷新桌面win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)http文件提供访问url的方法
from bs4 import BeautifulSoupimport requestsimport timeheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}#访问url,返回soup 方便控制访问频率,避免输入验证码def visitUrl(url):wb_data = requests.get(url, headers=headers)#print('webEncoding is ',wb_data.encoding)# wb_data.encoding = 'gbk'# print('webEncoding has set gbk')soup = BeautifulSoup(wb_data.text, 'lxml')time.sleep(0.2)return soupdef visitUrl_response(url):return requests.get(url, headers=headers)本次程序命名有很多不规范,有时间再改源码及地址 http://download.csdn.net/detail/felixzh123/9910229
相关文章推荐
- 用python实现下载必应壁纸并自动更换壁纸的功能
- 自己动手写Python实现Ubuntu自动切换壁纸
- python设置windows桌面壁纸的实现代码
- python实现自动更换ip的方法
- Python实现设置windows桌面壁纸代码分享
- 让 Ubuntu 桌面自动更换壁纸
- Python3实现Win10桌面背景自动切换
- 让 Ubuntu 桌面自动更换壁纸
- 让你的电脑多个桌面壁纸自动智能切换不用任何软件实现
- python实现自动更换ip的方法
- 关Python的小程序-更换桌面壁纸和下载网页
- 关于自动更换xp桌面的壁纸。
- python实现自动更换ip的方法
- python设置windows桌面壁纸的实现代码
- vb实现桌面墙纸自动更换
- python实现自动保存windows聚焦壁纸
- ubuntu 16.04LTS 开机启动自动更换壁纸的实现方法
- Python3.7实现中控考勤机自动连接
- 自动实现结构体打印--用python
- python学习之路之案例0(实现登录功能,登录错误次数超过3次,自动退出登录)