【Python自動更換桌面壁紙】爬取7000張4K超清壁紙,並制作自動更換桌面腳本,讓你的壁紙一年都不重復


前言

發現一個不錯的壁紙網站,里面都是超高清的圖片,而且還是免費為的。

所以,我打算把這些壁紙都爬取下來,然后在做一個自動跟換桌面壁紙的腳本,這樣基本上你一年都可以每天都有不重復桌面了

目標地址

先來看看我們這次的受害者:https://wallhaven.cc/

 

先是爬蟲代碼

導入數據

import requests
import re

 

請求數據

for page in range(1, 126):
    url = 'https://wallhaven.cc/toplist?page={}'.format(page)
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)

 

解析數據

urls = re.findall('<a class="preview" href="(.*?)"', response.text)
for i in urls:
    response_2 = requests.get(url=i, headers=headers)
    img_url = re.findall('<img id="wallpaper" src="(.*?)"', response_2.text)[0]
    title = img_url.split('-')[-1]
    download(title, img_url)
    print(img_url)

 

保存數據

def download(title, url):
    path = 'img\\' + title
    response = requests.get(url=url)
    with open(path, mode='wb') as f:
        f.write(response.content)

 

運行代碼,查看結果

自動跟換桌面壁紙代碼

import win32api
import win32con
import win32gui
import os
import time


def Windows_img(paperPath):
    k=win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control panel\\Desktop",0,win32con.KEY_SET_VALUE)
    # 在注冊表中寫入屬性值
    win32api.RegSetValueEx(k,"wapaperStyle",0,win32con.REG_SZ,"2")  # 0 代表桌面居中 2 代表拉伸桌面
    win32api.RegSetValueEx(k,"Tilewallpaper",0,win32con.REG_SZ,"0")
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,paperPath,win32con.SPIF_SENDWININICHANGE) # 刷新桌面


def changeWallpaper():
    """文件夾/文件夾/圖片"""
    path=input('請輸入文件路徑:')
    L2=os.listdir(path=path)  # 得到文件路徑下的壁紙文件夾,列表類型
    i=0
    print(L2)   # 壁紙文件夾
    url_list = []
    for l2 in L2:
        detail_path = path + '\\' + l2
        L3 = os.listdir(detail_path)    # 得到壁紙文件夾路徑下的圖片,列表類型
        for l3 in L3:
            url_list.append(detail_path + '\\' + l3)
    print(url_list)
    while True:
        Windows_img(url_list[i])
        print('{}'.format(url_list[i]))
        time.sleep(2)  # 設置壁紙更換間隔,這里為10秒,根據用戶自身需要自己設置秒數
        i += 1
        if i == len(url_list):  # 如果是最后一張圖片,則重新到第一張
            i = 0


def changeWallpaper_2():
    """文件夾/圖片"""
    path=input('請輸入文件路徑:')
    L2=os.listdir(path=path)  # 得到文件路徑下的圖片,列表類型
    i=0
    print(L2)
    while True:
        Windows_img(path+'\{}'.format(L2[i]))
        print(path+'\{}'.format(L2[i]))
        time.sleep(1000)  # 設置壁紙更換間隔,這里為10秒,根據用戶自身需要自己設置秒數
        i += 1
        if i==len(L2):  # 如果是最后一張圖片,則重新到第一張
            i=0

if __name__ == '__main__':
    changeWallpaper()

 

最后實現效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM