爬取Bing背景图设为壁纸

爬取Bing背景图设为壁纸

今天又是发现有趣小项目的一天,并且学到了一个新词———“脚本小子”,所谓脚本小子大概指的就是那些不会自己敲代码写程序,到处找源码的小菜鸟,比如说我。

今天要记录的是一个简单的爬虫项目,爬取Bing搜索的背景图并设为自己的电脑壁纸。
原帖在此

由于时间跨度有点久,网站源码里的背景图url格式有所改变,对代码做了少许修改后就又能跑通了(顺便学习了一波正则表达式的相关知识,只不过有些许看不进),代码如下

# **************
# coding=utf-8
# by ivor
# 设置bing.com背景为壁纸

import re
import requests
import pythoncom
from win32com.shell import shell, shellcon

class MyPaper:

    def __init__(self):
        self.image = r"C:\paper.jpg"
        self.url = r'https://cn.bing.com/'

    def getDeskComObject(self):
        self.g_desk = None
        if not self.g_desk:
            self.g_desk = pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, \
                                                     None, pythoncom.CLSCTX_INPROC_SERVER, \
                                                     shell.IID_IActiveDesktop)
        return self.g_desk

    def setWallPaper(self):
        self.desktop = self.getDeskComObject()
        if self.desktop:
            self.desktop.SetWallpaper(self.image, 0)
            self.desktop.ApplyChanges(shellcon.AD_APPLY_ALL)

    def addUrlLink(self, lnk):
        self.desktop = self.getDeskComObject()
        self.desktop.AddUrl(0, lnk, 0, 0)

    def imgDownload(self):
        r = requests.get(self.url).content
        pattern = re.compile(r'href="(.*jpg)?')
        imgUrl = re.findall(pattern, r.decode(encoding="utf-8"))
        print(imgUrl)
        imgData = requests.get(self.url + imgUrl[0]).content
        with open(self.image, "wb") as file:
            file.write(imgData)


setPaper = MyPaper()
setPaper.imgDownload()
setPaper.setWallPaper()

效果如下,nice
在这里插入图片描述
在这里插入图片描述
更绝的来了,在知乎上刷到了一个回答,答主的想法是给系统设置一个定时任务,每天执行上述代码,那样壁纸就会随着bing搜索背景图片的更新而更新
该回答链接在此

学到了,于是乎,我采用了上述方案,以后再也不用纠结换啥壁纸好了。哈哈哈哈哈

发布了7 篇原创文章 · 获赞 13 · 访问量 484

猜你喜欢

转载自blog.csdn.net/yc10d/article/details/103739498