• python实现抓取必应图片设置桌面


    源码参考https://github.com/vbirds/pyWallpaper,代码风格不错

    本人只是将其适配到python3.5,并消除一些bug,源代码中桌面地址未使用绝对路径导致win10 下无法成功设置桌面

    #python: 3.5
    #os: win10 home

    #-*-coding:utf-8-*-
    from PIL import Image
    import win32gui
    import win32con
    import win32api
    import os
    import threading
    import urllib.request
    import time
    import sys
    import json
    
    '''
    {
        "images":[
            {
                "startdate":"20170827",
                "fullstartdate":"201708271600",
                "enddate":"20170828",
                "url":"/az/hprichbg/rb/BotallackCornwall_ZH-CN11396172846_1920x1080.jpg",
                "urlbase":"/az/hprichbg/rb/BotallackCornwall_ZH-CN11396172846",
                "copyright":"康沃尔郡内的巴特莱克矿场, 英国 (© Robert Harding/Masterfile)",
                "copyrightlink":"http://www.bing.com/search?q=botallack+manor&form=hpcapt&mkt=zh-cn",
                "quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20170827_BotallackCornwall%22&FORM=HPQUIZ",
                "wp":true,
                "hsh":"5eb81f1029c57dfa1cc5f69ca871f4b1",
                "drk":1,
                "top":1,
                "bot":1,
                "hs":[]
            }
        ],
        "tooltips":{
            "loading":"正在加载...",
            "previous":"上一个图像",
            "next":"下一个图像",
            "walle":"此图片不能下载用作壁纸。",
            "walls":"下载今日美图。仅限用作桌面壁纸。"
        }
    }
    '''
    
    
    class Wallpaper:
    
        def __init__(self, time=60):
            self.count = 0
            if time <= 0 :
                self.time = 60
            self.time = time
            self.urltemplate = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=%d&n=1&nc=1361089515117&FORM=HYLH1'
            self.baImageUrlList = []
            self.localFileName  = ''
            self.localBMPFileName  = ''
            self.imagedir = './images/'
            self.bmpdir = './bmpimage/'
            self.bmplist = []
    
        def start(self):
            self.prepareDir()
            self.parserImageUrl()
            self.download_images()
            self.image_convert_bmp()
            self.set_wall_func()
    
        def prepareDir(self):
            if not os.path.exists(self.imagedir):
                os.makedirs(self.imagedir)
            if not os.path.exists(self.bmpdir):
                os.makedirs(self.bmpdir)
             
        def parserImageUrl(self):
    
            for i in range(0, 7, 1):
                url = self.urltemplate % i #use i replace format 
                try:
                    content = urllib.request.urlopen(url,None).read().decode("utf-8")# 由于有中文,decode("utf-8")必须
                except:
                    print(url)
                    print("parse try again")
                decodedjson = json.loads(content)
                imageurl = decodedjson['images'][0]['url']
    
                self.baImageUrlList.append('https://cn.bing.com'+imageurl)
    
        def download_images(self):
    
            for url in self.baImageUrlList:
                imagename = os.path.basename(url)
                imagepath = self.imagedir + imagename
                print(imagepath)
                f = open(imagepath, 'wb')
                try:
                    conn = urllib.request.urlopen(url)
                except:
                    print(url)
                    print("download try again")
                f.write(conn.read())
                f.close()
    
        def image_convert_bmp(self):
            imaglist = os.listdir(self.imagedir)
            for imagepath in imaglist:
                file_name = os.path.basename(imagepath)
                file_name_type = os.path.splitext(file_name)
                file_name = file_name_type[0]
                newpath = self.bmpdir + file_name + '.bmp'
                imagepath  = './images/' + imagepath
    
                bmpImage = Image.open(imagepath)
                bmpImage.save(newpath, "BMP")
                self.bmplist.append(sys.path[0]+'\bmpimage\'+file_name + '.bmp')
    
        def setWallpaper(self, imagepath):
            k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\Desktop",0,win32con.KEY_SET_VALUE)
            win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2") #2拉伸适应桌面,0桌面居中
            win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
            print(imagepath)
            win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,imagepath, 1+2)#文件需要使用完整路径
    
        def set_wall_func(self):
            list_size = len(self.bmplist)
            index = self.count % list_size
            filename = self.bmplist[index]
            self.count += 1
            self.setWallpaper(filename)
            self.set_wall_timer()
    
        def set_wall_timer(self):
            timer = threading.Timer(self.time, self.set_wall_func)
            timer.start()
    
    
    
    if __name__ == '__main__':
    
        bing = Wallpaper(300)
        bing.start()
  • 相关阅读:
    PSE Access Service
    The JXTA Migration
    JXSE 2.5 : What's Cool #6 PeerGroup Executor and ScheduledExcutor
    JXTA Kitchen
    LookupListener中的resultChanged方法是在EDT中执行么?
    同一台机器启动两个结点时的端口冲突问题
    (转)OpenSSL中对称加密算法的统一接口
    关于“未能加载文件或程序集“System.Core, Version=3.5.0.0
    暗香浮动的夜晚
    java xml序列化与反序列化
  • 原文地址:https://www.cnblogs.com/hixin/p/7444214.html
Copyright © 2020-2023  润新知