1. 为什么需要自动下载壁纸的Python脚本
每天手动更换壁纸对很多人来说是个麻烦事。我曾在Windows上设置过系统自带的壁纸轮换功能,但很快就发现几个痛点:可选图片数量有限、更新频率低、无法按个人喜好筛选。更糟的是,系统自带的壁纸库往往充斥着大量我不感兴趣的风景照和抽象图案。
Python脚本可以完美解决这些问题。通过编写一个简单的爬虫程序,我们能够:
- 从高质量的壁纸网站抓取最新图片
- 按指定分辨率自动筛选
- 根据个人偏好下载特定类别(比如科技、动漫、极简风格)
- 设置定时任务实现全自动更新
最近我帮朋友配置了这样一个脚本,他反馈说现在每天开机都能看到新鲜的高清壁纸,工作效率都提高了不少。这让我意识到,虽然是个小工具,但确实能提升日常使用体验。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 准备工作与环境配置
2.1 Python环境检查
首先确认你的Python版本。打开命令行输入:
bash复制python --version
# 或
python3 --version
建议使用Python 3.6及以上版本。如果尚未安装,可以从官网下载最新稳定版。安装时务必勾选"Add Python to PATH"选项。
2.2 必备库安装
我们需要以下几个关键库:
bash复制pip install requests beautifulsoup4 pillow schedule
requests:用于发送HTTP请求获取网页内容beautifulsoup4:解析HTML页面,提取图片链接pillow:处理图片下载和格式转换schedule:设置定时任务
注意:国内用户如果下载速度慢,可以使用清华镜像源:
bash复制pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests beautifulsoup4 pillow schedule
2.3 创建项目目录
建议建立如下目录结构:
code复制/wallpaper_downloader
/config
settings.ini
/wallpapers
main.py
wallpapers文件夹将用于存储下载的图片,建议放在非系统分区,避免占用C盘空间。
3. 核心爬虫功能实现
3.1 选择壁纸来源网站
经过测试,以下几个网站适合作为图片来源:
- Wallhaven.cc(需注册API key)
- Unsplash.com(有官方API)
- Bing每日壁纸
- Desktoppr.co
以Unsplash为例,它提供免费的API接口,每天可以请求50次,完全够个人使用。
3.2 编写下载函数
python复制import requests
import os
from PIL import Image
from io import BytesIO
def download_wallpaper(url, save_path, resolution=(1920, 1080)):
try:
response = requests.get(url, stream=True)
response.raise_for_status()
img = Image.open(BytesIO(response.content))
img = img.resize(resolution, Image.LANCZOS)
if not os.path.exists(os.path.dirname(save_path)):
os.makedirs(os.path.dirname(save_path))
img.save(save_path, quality=95)
print(f"成功下载: {save_path}")
return True
except Exception as e:
print(f"下载失败: {str(e)}")
return False
这个函数做了几件事:
- 流式下载图片数据(避免内存溢出)
- 自动调整到指定分辨率
- 保存为高质量JPEG
- 完善的错误处理
3.3 解析网页获取图片链接
以Wallhaven为例的解析代码:
python复制from bs4 import BeautifulSoup
def get_wallhaven_links(page_url, min_width=1920):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
try:
response = requests.get(page_url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
wallpapers = []
for img in soup.select('figure img.lazyload'):
src = img['data-src'].replace('//th.', '//w.')
if 'full' in src and int(src.split('/')[5].split('x')[0]) >= min_width:
wallpapers.append(src)
return wallpapers
except Exception as e:
print(f"解析失败: {str(e)}")
return []
这段代码的关键点:
- 使用懒加载图片的data-src属性
- 替换缩略图URL为原图URL
- 过滤低于指定宽度的图片
4. 完整脚本整合与优化
4.1 配置文件设计
在config/settings.ini中添加:
ini复制[wallhaven]
api_key = YOUR_API_KEY
categories = general,anime
purity = sfw
resolutions = 1920x1080,2560x1440
[unsplash]
query = nature,technology
orientation = landscape
[storage]
download_path = ./wallpapers
max_files = 50
4.2 主程序逻辑
python复制import configparser
import time
from datetime import datetime
def main():
config = configparser.ConfigParser()
config.read('config/settings.ini')
# 清理旧文件
clean_old_files(config['storage']['download_path'],
int(config['storage']['max_files']))
# 获取多个来源的壁纸
sources = [
get_wallhaven_wallpapers,
get_unsplash_wallpapers
]
for source in sources:
try:
urls = source(config)
for url in urls:
filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
save_path = os.path.join(config['storage']['download_path'], filename)
if download_wallpaper(url, save_path):
time.sleep(2) # 礼貌性延迟
except Exception as e:
print(f"源 {source.__name__} 出错: {str(e)}")
def clean_old_files(folder, keep_max):
files = sorted([f for f in os.listdir(folder) if f.endswith('.jpg')],
key=lambda x: os.path.getmtime(os.path.join(folder, x)))
while len(files) > keep_max:
os.remove(os.path.join(folder, files.pop(0)))
4.3 定时任务设置
使用schedule库实现每天自动运行:
python复制import schedule
def job():
print("开始执行壁纸下载任务...")
main()
print("任务完成")
# 每天上午10点运行
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
5. 实用技巧与问题排查
5.1 提高下载成功率
- User-Agent轮换:准备多个常见浏览器的User-Agent字符串,随机选择使用
python复制user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
]
headers = {'User-Agent': random.choice(user_agents)}
- 代理设置:如果需要,可以配置代理
python复制proxies = {
'http': 'http://your_proxy:port',
'https': 'https://your_proxy:port'
}
response = requests.get(url, headers=headers, proxies=proxies)
5.2 常见错误处理
- SSL证书错误:
python复制import urllib3
urllib3.disable_warnings()
response = requests.get(url, verify=False)
- 连接超时:
python复制try:
response = requests.get(url, timeout=10)
except requests.exceptions.Timeout:
print("请求超时,正在重试...")
time.sleep(5)
continue
- 图片损坏:
python复制from PIL import Image
try:
Image.open(image_path).verify()
except:
os.remove(image_path)
5.3 进阶功能扩展
- 自动设置壁纸(Windows):
python复制import ctypes
def set_wallpaper(path):
ctypes.windll.user32.SystemParametersInfoW(20, 0, path, 3)
- 多显示器支持:
python复制# 下载多张图片后拼接
images = [Image.open(f) for f in image_paths]
total_width = sum(img.width for img in images)
max_height = max(img.height for img in images)
new_img = Image.new('RGB', (total_width, max_height))
x_offset = 0
for img in images:
new_img.paste(img, (x_offset,0))
x_offset += img.width
new_img.save('combined.jpg')
- 主题颜色分析:
python复制from colorthief import ColorThief
def get_dominant_color(image_path):
color_thief = ColorThief(image_path)
return color_thief.get_color(quality=1)
6. 实际使用建议
经过几个月的实际使用,我发现这些设置最合理:
-
存储管理:设置保留50-100张最新壁纸为宜,太多会占用空间,太少缺乏多样性
-
下载频率:每天1-2次足够,过于频繁可能被网站封禁
-
分辨率选择:根据自己最常用的显示器分辨率设置,我建议:
- 笔记本:1920x1080
- 4K显示器:3840x2160
- 多显示器:选择最大宽度
-
分类策略:可以按星期设置不同主题,比如:
- 周一:科技感图片
- 周三:自然风景
- 周五:动漫/艺术
-
性能优化:如果脚本运行缓慢,可以:
- 减少同时查询的网站数量
- 降低图片质量(85-90即可)
- 使用多线程下载(但要注意礼貌延迟)
这个脚本我已经稳定使用了一年多,期间只做过少量调整。它最大的价值在于完全自动化了一个原本需要手动操作的流程,而且可以根据个人品味持续提供高质量的壁纸选择。对于Python初学者来说,这也是个很好的练手项目,涵盖了网络请求、文件操作、定时任务等多个实用技能点。
