筆者想每天更換Bing壁紙,但是不想用安裝BingDesktop,因?yàn)檫@款官方軟件沒辦法下載壁紙。故準(zhǔn)備寫一個(gè)腳本,加入到Windows計(jì)劃任務(wù)里邊去,定時(shí)執(zhí)行。
思路很簡(jiǎn)單。自己搜索了下,有2種比較簡(jiǎn)單的辦法可以嘗試。
方法1給出了完整代碼,方法2是部分代碼。
方法1:可以用網(wǎng)上給的比較多的一個(gè)接口,我沒有找到這個(gè)接口的出處,但是無論是國外的論壇stackvoerflow還是國內(nèi)的博客里面主要都是用的這個(gè)接口, 返回的是json。
https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US
更詳細(xì)的其他接口可以看看。
StackOverflow鏈接地址戳我
方法2:爬取bing官網(wǎng),找到固定標(biāo)簽,獲取圖片url。
筆者認(rèn)為方法1更簡(jiǎn)單,方法2稍微麻煩了點(diǎn)。
方法2:
# -*- coding: utf-8 -*-
import asyncio
import aiohttp
from bs4 import BeautifulSoup
BING = "https://www.bing.com"
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
async def main():
async with aiohttp.ClientSession() as session:
async with session.get(BING, headers=HEADERS) as response:
text = await response.content.read()
soup = BeautifulSoup(text.decode(), 'html.parser')
tag = soup.find('a', attrs={'class': 'downloadLink'})
title = soup.find('a', attrs={'class': 'title'}).text
print('url %s' % tag.attrs.get('href'))
print('title %s' % title)
if '__main__' == __name__:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
url /th?id=OHR.CosmicCliffs_ZH-CN9555199651_1920x1200.jpg&rf=LaDigue_1920x1200.jpg
title 船底星云中的宇宙懸崖
值得注意的一點(diǎn)是這樣下載的壁紙是1920X1200的分辨率,并且壁紙是有水印的。
域名 + 上下文就可以訪問到Bing壁紙了
https://cn.bing.com/th?id=OHR.CosmicCliffs_ZH-CN9555199651_1920x1080.jpg
https://bing.com/th?id=OHR.CosmicCliffs_ZH-CN9555199651_1920x1200.jpg
https://cn.bing.com/th?id=OHR.CosmicCliffs_ZH-CN9555199651_1920x1080.jpg&rf=LaDigue_1920x1200.jpg

image.png
只要把url里面的1200這個(gè)值改為1080,這樣就沒有水印了。
方法1:
在D盤創(chuàng)建一個(gè)文件夾WallPaper用來保存下載的壁紙,再執(zhí)行Python腳本。
# -*- coding: utf-8 -*-
import time
import re
import os
import aiohttp
import asyncio
import ctypes
SPI_SET_DESK_WALLPAPER = 20
BING = "https://www.bing.com"
SAVE = r"D:\WallPaper"
HEADERS = {}
def change_background(path):
"""
設(shè)置系統(tǒng)壁紙
:param path:
:return:
"""
ctypes.windll.user32.SystemParametersInfoW(SPI_SET_DESK_WALLPAPER, 0, path, 3)
def check_name_valid(name=None):
"""
處理文件名里面的特殊字符(空格等)
:param name:
:return:
"""
if name is None:
return False
reg = re.compile(r'[\\/:*>"<>|\r\n]+')
valid_name = reg.findall(name)
if valid_name:
for nv in valid_name:
name = name.replace(nv, '')
return name
async def main():
try:
async with aiohttp.ClientSession() as session:
async with session.get('https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US', headers=HEADERS) as response:
content = await response.json()
title = content['images'][0]['copyright'] + '.jpg'
title = check_name_valid(title)
target = BING + content['images'][0]['url']
background_location = os.path.join(SAVE, title)
if not os.path.exists(background_location):
async with session.get(target, headers=HEADERS) as wallpaper_response:
content = await wallpaper_response.content.read()
with open(background_location, 'wb') as f:
f.write(content)
print('download image success.')
print('set windows wallpaper success.')
else:
print('already download wallpaper.')
change_background(path=background_location)
except Exception as e:
print(e)
if '__main__' == __name__:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
title: 船底星云中的宇宙懸崖 (? NASA, ESA, CSA, and STScI).jpg
target: https://www.bing.com/th?id=OHR.CosmicCliffs_ZH-CN9555199651_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp

image.png
這樣就完事了,剩下的就是把這個(gè)腳本加入windows計(jì)劃任務(wù),設(shè)置每天定時(shí)執(zhí)行。
可能存在的問題:如果電腦有梯子,可能通過Python腳本得到的壁紙Json信息和瀏覽器得到的不同,需要設(shè)置下proxy。不設(shè)置也沒有特別影響,無論是大陸版還是國際版壁紙都能更新。