美文网首页
Python自动更换Bing壁纸

Python自动更换Bing壁纸

作者: BoatingTao | 来源:发表于2022-11-19 13:32 被阅读0次

笔者想每天更换Bing壁纸,但是不想用安装BingDesktop,因为这款官方软件没办法下载壁纸。故准备写一个脚本,加入到Windows计划任务里边去,定时执行。

思路很简单。自己搜索了下,有2种比较简单的办法可以尝试。
方法1给出了完整代码,方法2是部分代码。

方法1:可以用网上给的比较多的一个接口,我没有找到这个接口的出处,但是无论是国外的论坛stackvoerflow还是国内的博客里面主要都是用的这个接口, 返回的是json。

https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US

更详细的其他接口可以看看。
StackOverflow链接地址戳我

方法2:爬取bing官网,找到固定标签,获取图片url。

笔者认为方法1更简单,方法2稍微麻烦了点。

方法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 船底星云中的宇宙悬崖

值得注意的一点是这样下载的壁纸是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这个值改为1080,这样就没有水印了。

方法1:
在D盘创建一个文件夹WallPaper用来保存下载的壁纸,再执行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):
    """
    设置系统壁纸
    :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

这样就完事了,剩下的就是把这个脚本加入windows计划任务,设置每天定时执行。

可能存在的问题:如果电脑有梯子,可能通过Python脚本得到的壁纸Json信息和浏览器得到的不同,需要设置下proxy。不设置也没有特别影响,无论是大陆版还是国际版壁纸都能更新。

相关文章

网友评论

      本文标题:Python自动更换Bing壁纸

      本文链接:https://www.haomeiwen.com/subject/zwsbxdtx.html