先介绍一个网站——句子迷,网站上有众多网友分享的经典句子,我们将搜索我们喜欢的作者,爬取所有该作者的名句。
我们利用selenium来进行可视化的爬虫,首先要pip install selenium,然后下载谷歌chrome浏览器的驱动,选择对应的版本即可。下载后解压,将路径添加到系统环境变量中,方便使用。
首先运行get_motto.py 来获得句子,存为mottos.json 和motto.txt。mottos.json 包含‘author’,'title', ‘paragraphs'。后面读取这个json文件,随机选取一句话,显示到桌面背景上。
get_motto.py
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 15:39:49 2018
@author: xiaozhen
"""
import time
import re
import json
from selenium import webdriver
starttime = time.time()
option = webdriver.ChromeOptions()
# option.add_argument('headless')
browser = webdriver.Chrome(chrome_options=option)
browser.minimize_window()
authors = "沈从文 王维 E·B·怀特 张爱玲 汪曾祺"
authors = ['李白', '木心', '鲁迅', '王尔德'] + authors.split()
# authors = ['李白']
motto_content = []
motto_txt = open('motto.txt', 'w', encoding='utf-8')
for author in authors:
motto_txt.write('\n\n# ' + author +
'\n------------------------------------\n')
browser.get(u"https://www.juzimi.com")
browser.find_element_by_id('edit-search-theme-form-1').send_keys(author)
browser.find_element_by_id('edit-submit-1').click()
pages = browser.find_element_by_class_name('pager-last')
pages = int(pages.text)
# author_motto = []
for page in range(pages):
print(f'{author} page:{page}/{pages}')
try:
# mottos = browser.find_elements_by_class_name('xlistju')
mottos = browser.find_elements_by_class_name('views-row')
for motto in mottos:
t = motto.text
t = t.split('喜欢')[0]
# print(t)
title = re.search(u'《(.*)》', t)
if title:
title = title.group(1)
else:
title = ''
content = t.split('——')[0]
# author_motto.append(motto.text)
motto_txt.write(t + '\n\n')
motto_content.append(
{'author': author, 'title': title,
'paragraphs': [content]})
print(motto_content[-1])
if page < pages:
browser.find_element_by_class_name('pager-next').click()
except UnicodeEncodeError:
if page < pages:
browser.find_element_by_class_name('pager-next').click()
except Exception as e:
print(e)
browser.close()
motto_txt.close()
with open('motto.json', 'w', encoding='utf-8') as f:
json.dump(motto_content, f)
print(f'finished {time.time()-starttime}s')
运行set_wallpaper.py,利用PIL中的ImageDraw,把文字添加到图片上,再将图片设置为桌面背景,每隔一段时间将随机选择一张图片,一种字体,一句话,合并为一张新图片,设置为桌面背景。需要将图片预先放在bgpics文件夹,字体放在fonts文件夹,下载好的mottos.json和脚本放在同一文件夹。
主要用到pywin32这个库用来设置桌面,以及apscheduler用来定时执行任务。都可以通过pip直接安装。文件夹目录如下:
set_wallpaper.py
mottos.json
bgpics/
-----wallpaper1.jpg
------wallpeper2.jpg
fonts/
------font1.ttf
------font2.ttf
set_wallpaper.py
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 11:30:56 2018
@author: xiaozhen
"""
import os, json
from PIL import Image, ImageFont, ImageDraw
import win32api
import win32con
import win32gui
import random
from apscheduler.schedulers.blocking import BlockingScheduler
def reformat(string):
string_lst = string.splitlines()
format_string = []
for line in string_lst:
for i in range(len(line)//25+1):
format_string.append(line[i*25:25*(i+1)])
return '\n'.join(format_string)
def set_wallpaper_from_bmp(bmp_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, bmp_path, win32con.SPIF_SENDWININICHANGE)
def random_poems(poet_files):
poet_file = random.choice(poet_files)
with open(poet_file, 'r', encoding='utf-8') as json_file:
poems = json.load(json_file)
poem = random.choice(poems)
poem_content = poem['paragraphs'][0]
poem['paragraphs'] = [reformat(poem_content)]
poem_string = '\n'.join([poem['title'], poem['author']] + poem['paragraphs'])
return poem_string
def set_wallpaper(img_files, poem_files):
# 把图片格式统一转换成bmp格式,并放在源图片的同一目录
img_path = random.choice(img_files)
img_dir = os.path.dirname(img_path)
bmpImage = Image.open(img_path)
bmpImage = bmpImage.resize((1920, 1080), Image.ANTIALIAS)
draw = ImageDraw.Draw(bmpImage)
font = random.choice([os.path.join('fonts', file)
for file in os.listdir('fonts')])
print(font)
fnt = ImageFont.truetype(font, 40)
poem_str = random_poems(poem_files)
print(poem_str)
width, height = bmpImage.size
draw.multiline_text((width/4, height/5), poem_str, fill='#000000',
font=fnt, anchor='center', spacing=10, align="center")
new_bmp_path = os.path.join(img_dir, 'wallpaper.bmp')
bmpImage.save(new_bmp_path, "BMP")
# here you need to provide the absolute path of the background picture
set_wallpaper_from_bmp(os.path.abspath(new_bmp_path))
if __name__ == '__main__':
pic_path = 'bgpics'
pic_files = [os.path.join(pic_path, file) for file in os.listdir(pic_path)
if 'wallpaper' not in file]
poet_files = ['mottos.json']
set_wallpaper(pic_files, poet_files)
scheduler = BlockingScheduler()
scheduler.add_job(set_wallpaper, args=(pic_files, poet_files,),
trigger='interval', seconds=120) # 设置间隔时间
scheduler.start()
最终桌面的效果如下:
桌面背景会一定时间自动更换。
可以写一个set_wallpaper.bat 文件:python set_wallpaper.py
复制set_wallpaper.bat的快捷方式到windows启动项中,这样每次开机就可以自动运行这个程序。
添加开机启动项:按下【Win+R】组合键打开运行窗口,输入:%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 点击确定。复制set_wallpaper.bat, 切换到启动项的文件夹中,右击选择粘贴快捷方式。
这样以后,每次开机桌面更换的程序也就随之启动了。可以从这里下载一个试用版。
GitHub 地址:https://github.com/xiaodaxia-2008/WallPaper