爬取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()
效果如下
在知乎上刷到了一个回答,答主的想法是给系统设置一个定时任务,每天执行上述代码,那样壁纸就会随着bing搜索背景图片的更新而更新
链接在此