用Python抓冰壁纸?

2024-05-20 17:20:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个python脚本必应贴墙纸并保存。在

这些墙纸的URL如下所示:

http://www.bing.com/az/hprichbg/rb/EuropeESA_DE-DE7849418832_1920x1080.jpg
http://www.bing.com/az/hprichbg/rb/CanisLupus_DE-DE11366975292_1920x1080.jpg
http://www.bing.com/az/hprichbg/rb/HouseBoats_DE-DE8695714746_1920x1080.jpg

有没有办法自动找到今天壁纸的图片网址?在


Tags: 脚本comhttpurl墙纸wwwdeaz
3条回答

基于本文related SO question中的一些有用答案,下面是一个简单的Python脚本来获取当天的Bing照片:

import requests
import json

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

# open the Bing HPImageArchive URI and ask for a JSON response
resp = requests.get(BING_URI_BASE + BING_WALLPAPER_PATH)

if resp.status_code == 200:
    json_response = json.loads(resp.content)
    wallpaper_path = json_response['images'][0]['url']
    filename = wallpaper_path.split('/')[-1]
    wallpaper_uri = BING_URI_BASE + wallpaper_path

    # open the actual wallpaper uri, and write the response as an image on the filesystem
    response = requests.get(wallpaper_uri)
    if resp.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)
    else:
        raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(wallpaper_uri))
else: 
    raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(BING_URI_BASE + BING_WALLPAPER_PATH))

这将向执行脚本的同一目录写入一个文件,如TurtleTears_EN-US7942276596_1920x1080.jpg。当然,可以在这里调整一大堆事情,但可以很容易地完成任务。在

使用以下代码获取并保存在文件夹中:

import datetime
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
import os
import sys


def join_path(*args):
    # Takes an list of values or multiple values and returns an valid path.
    if isinstance(args[0], list):
        path_list = args[0]
    else:
        path_list = args
    val = [str(v).strip(' ') for v in path_list]
    return os.path.normpath('/'.join(val))

dir_path = os.path.dirname(os.path.realpath(__file__))
save_dir = join_path(dir_path, 'images')
if not os.path.exists(save_dir):
    os.makedirs(save_dir)


def set_wallpaper(pic_path):
    if sys.platform.startswith('win32'):
        cmd = 'REG ADD \"HKCU\Control Panel\Desktop\" /v Wallpaper /t REG_SZ /d \"%s\" /f' %pic_path
        os.system(cmd)
        os.system('rundll32.exe user32.dll, UpdatePerUserSystemParameters')
        print('Wallpaper is set.')
    elif sys.platform.startswith('linux'):
        os.system(''.join(['gsettings set org.gnome.desktop.background picture-uri file://', pic_path]))
        print('Wallpaper is set.')
    else:
        print('OS not supported.')
        return
    return


def download_old_wallpapers(minus_days=False):
    """Uses download_wallpaper(set_wallpaper=False) to download the last 20 wallpapers.
    If minus_days is given an integer a specific day in the past will be downloaded.
    """
    if minus_days:
        download_wallpaper(idx=minus_days, use_wallpaper=False)
        return
    for i in range(0, 20):  # max 20
        download_wallpaper(idx=i, use_wallpaper=False)


def download_wallpaper(idx=0, use_wallpaper=True):
    # Getting the XML File
    try:
        usock = urlopen(''.join(['http://www.bing.com/HPImageArchive.aspx?format=xml&idx=',
                                 str(idx), '&n=1&mkt=ru-RU']))  # ru-RU, because they always have 1920x1200 resolution
    except Exception as e:
        print('Error while downloading #', idx, e)
        return
    try:
        xmldoc = minidom.parse(usock)
    # This is raised when there is trouble finding the image url.
    except Exception as e:
        print('Error while processing XML index #', idx, e)
        return
    # Parsing the XML File
    for element in xmldoc.getElementsByTagName('url'):
        url = 'http://www.bing.com' + element.firstChild.nodeValue
        # Get Current Date as fileName for the downloaded Picture
        now = datetime.datetime.now()
        date = now - datetime.timedelta(days=int(idx))
        pic_path = join_path(save_dir, ''.join([date.strftime('bing_wp_%d-%m-%Y'), '.jpg']))
        if os.path.isfile(pic_path):
            print('Image of', date.strftime('%d-%m-%Y'), 'already downloaded.')
            if use_wallpaper:
                set_wallpaper(pic_path)
            return
        print('Downloading: ', date.strftime('%d-%m-%Y'), 'index #', idx)

        # Download and Save the Picture
        # Get a higher resolution by replacing the file name
        urlretrieve(url.replace('_1366x768', '_1920x1200'), pic_path)
        # Set Wallpaper if wanted by user
        if use_wallpaper:
            set_wallpaper(pic_path)


if __name__ == "__main__":
    download_wallpaper()
for number, url in enumerate(list_of_urls):
    urllib.urlretrieve(url, 'Image {}.jpg'.format(number + 1))

相关问题 更多 >