日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 实现桌面壁纸自动更换

發布時間:2023/12/14 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 实现桌面壁纸自动更换 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

學了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 timedef setBgUrl():#睡五秒鐘,等待另一個線程爬取圖片utl 這樣可以運行程序,立即更換桌面 time.sleep(5)print('setBgUrl has executed')pic_urls = getBgUrls.pic_urlsif 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 = urlselse :db.removeDb()fileUtils.removeAllPic()t1 = threading.Thread(target=getBgUrls.get_pic_urls_to_db).start()setBgUrl() db文件,負責數據庫的操作。數據庫用的是python自帶的sqlite,還挺好用的

import sqlite3 import os print('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)") #初始化為0conn_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) + 1sql = "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 Http from win32api import GetSystemMetrics import db pic_urls = [] # 存儲所有的圖片url #解析網站,獲取圖片url def 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 Http import 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#截取url file_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:continue else :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表示平鋪,拉伸居中等都是0 win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")# 刷新桌面 win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, img_path, win32con.SPIF_SENDWININICHANGE)


http文件提供訪問url的方法

from bs4 import BeautifulSoup import requests import 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 实现桌面壁纸自动更换的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。