lsekfe 发表于 2023-2-8 11:39:36

Python小技能---下载壁纸并自动更换桌面

壁纸 API
  我们这里使用一个开源在 GitHub 上的必应壁纸 API 作为壁纸的来源
  https://github.com/zenghongtu/bing-wallpaper
http://www.51testing.com/attachments/2023/02/15326880_2023020710590919VzM.png
  从 readme 当中我们可以知道,在 web 应用中我只需要使用如下引用即可
  <img src="https://bingw.jasonzeng.dev/?w=800"/>


实在是太方便了
  接口使用
  下面我们来看下该 API 的具体调用规则
  1、传入 resolution 参数可以指定壁纸图像的分辨率。默认为1920x1080,可选值如下:
 UHD
  1920x1200
  1920x1080
  1366x768
  1280x768
  1024x768
  800x600
  800x480
  768x1280
  720x1280
  640x480
  480x800
  400x240
  320x240
  240x320

UHD 就是高清,图片比较大。
  2、传入 index 可以获取某一天的图片,0 表示今天,1 表示昨天,以此类推,index=random 表示随机一天。
  3、传入 date 可以获取从某一天到今天的图片,比如 data=20210401。
  4、传入 w 和 h 可以指定图片的宽度和高度。
  5、传入 qlt 可以指定图片的质量,取值范围是 0 到 100。
  举个例子
  我们直接在浏览器输入如下地址
  http://bingw.jasonzeng.dev?resolutinotallow=UHD&index=random&w=1000&format=json


Output:
{
   "startdate": "20220105",
   "copyright": "Plate-billed mountain toucan in Bellavista Cloud Forest Reserve, Ecuador (? Tui De Roy/Minden Pictures)",
   "urlbase": "/th?id=OHR.MountainToucan_EN-US7120632569",
   "title": "A plate-billed mountain toucan",
   "url": "https://www.bing.com/th?id=OHR.MountainToucan_EN-US7120632569_UHD.jpg&w=1000"
  }

可以说是相当方便了。
  也可以直接在 css 当中使用。
background-image: url(https://bingw.jasonzeng.dev/?index=random);
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;

Python 调用
  下面我们看一下如何通过 Python 进行调用,也很简单
 import requests
  def get_wallpaper():
      for i in range(30):
        url = "https://bingw.jasonzeng.dev?resolutinotallow=UHD&index=%s" % str(i)
        print(url)
        res = requests.get(url)
        with open("wallpaper/" + "%s.jpg" % str(i),"wb") as w:
              w.write(res.content)
  if __name__ == "__main__":
      get_wallpaper()

上面代码就是获取前30张壁纸,我们可以修改range的参数,来获取不同数量的壁纸
  抓取效果如下:
http://www.51testing.com/attachments/2023/02/15326880_202302071059111rTuT.png
  更换桌面
  壁纸有了,下面我们就来进行自动切换桌面壁纸,这里使用win32con和win32gui操作桌面壁纸
def windows_img(paper_path):
      k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control panel\\Desktop", 0, win32con.KEY_SET_VALUE) # 在注册表中写入属性值
      win32api.RegSetValueEx(k, "wapaperStyle", 0, win32con.REG_SZ,"2")# 0 代表桌面居中 2 代表拉伸桌面
      win32api.RegSetValueEx(k, "Tilewallpaper", 0, win32con.REG_SZ,"0")
      win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, paper_path, win32con.SPIF_SENDWININICHANGE) # 刷新桌面

然后就是从已经下载的壁纸当中选择图片
def change_wallpaper():
      pic_list = os.listdir("wallpaper")# 得到文件路径下的图片,列表类型
      i=0
      print(pic_list)
      while True:
        pic = "wallpaper"+'\{}'.format(pic_list)
        abspath_pic = os.path.abspath(pic)
        windows_img(abspath_pic)
        print(abspath_pic)
        time.sleep(1000)# 设置壁纸更换间隔
        i += 1
        if i==len(pic_list):# 如果是最后一张图片,则重新到第一张
              i=0
  if __name__ == '__main__':
      change_wallpaper()

这样一个简单的自动切换桌面壁纸的工具就完成了,快来尝试一下吧!






页: [1]
查看完整版本: Python小技能---下载壁纸并自动更换桌面