Вопрос по – Есть ли способ получить фото дня Бинга?

81

Есть ли какой-нибудь способ получить фоновое изображение Bing программным способом?

Похоже, что API Bing не предоставляет такую функциональность, возможно, есть другой способ?

Ваш Ответ

19   ответов
3

RSS:

2

using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace BingBackground
{
    class BingBackground
    {
        private static void Main(string[] args)
        {
            string urlBase = GetBackgroundUrlBase();
            Image background = DownloadBackground(urlBase + GetResolutionExtension(urlBase));
            SaveBackground(background);
            SetBackground(background, PicturePosition.Fill);
        }

        private static dynamic DownloadJson()
        {
            using (WebClient webClient = new WebClient())
            {
                Console.WriteLine("Downloading JSON...");
                string jsonString = webClient.DownloadString("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US");
                return JsonConvert.DeserializeObject<dynamic>(jsonString);
            }
        }

        private static string GetBackgroundUrlBase()
        {
            dynamic jsonObject = DownloadJson();
            return "https://www.bing.com" + jsonObject.images[0].urlbase;
        }

        private static string GetBackgroundTitle()
        {
            dynamic jsonObject = DownloadJson();
            string copyrightText = jsonObject.images[0].copyright;
            return copyrightText.Substring(0, copyrightText.IndexOf(" ("));
        }

        private static bool WebsiteExists(string url)
        {
            try
            {
                WebRequest request = WebRequest.Create(url);
                request.Method = "HEAD";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return response.StatusCode == HttpStatusCode.OK;
            }
            catch
            {
                return false;
            }
        }

        private static string GetResolutionExtension(string url)
        {
            Rectangle resolution = Screen.PrimaryScreen.Bounds;
            string widthByHeight = resolution.Width + "x" + resolution.Height;
            string potentialExtension = "_" + widthByHeight + ".jpg";
            if (WebsiteExists(url + potentialExtension))
            {
                Console.WriteLine("Background for " + widthByHeight + " found.");
                return potentialExtension;
            }
            else
            {
                Console.WriteLine("No background for " + widthByHeight + " was found.");
                Console.WriteLine("Using 1920x1080 instead.");
                return "_1920x1080.jpg";
            }
        }

        private static Image DownloadBackground(string url)
        {
            Console.WriteLine("Downloading background...");
            WebRequest request = WebRequest.Create(url);
            WebResponse reponse = request.GetResponse();
            Stream stream = reponse.GetResponseStream();
            return Image.FromStream(stream);
        }

        private static string GetBackgroundImagePath()
        {
            string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Bing Backgrounds", DateTime.Now.Year.ToString());
            Directory.CreateDirectory(directory);
            return Path.Combine(directory, DateTime.Now.ToString("M-d-yyyy") + ".bmp");
        }

        private static void SaveBackground(Image background)
        {
            Console.WriteLine("Saving background...");
            background.Save(GetBackgroundImagePath(), System.Drawing.Imaging.ImageFormat.Bmp);
        }

        private enum PicturePosition
        {
            Tile,
            Center,
            Stretch,
            Fit,
            Fill
        }

        internal sealed class NativeMethods
        {
            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            internal static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        }

        private static void SetBackground(Image background, PicturePosition style)
        {
            Console.WriteLine("Setting background...");
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Path.Combine("Control Panel", "Desktop"), true))
            {
                switch (style)
                {
                    case PicturePosition.Tile:
                        key.SetValue("PicturePosition", "0");
                        key.SetValue("TileWallpaper", "1");
                        break;
                    case PicturePosition.Center:
                        key.SetValue("PicturePosition", "0");
                        key.SetValue("TileWallpaper", "0");
                        break;
                    case PicturePosition.Stretch:
                        key.SetValue("PicturePosition", "2");
                        key.SetValue("TileWallpaper", "0");
                        break;
                    case PicturePosition.Fit:
                        key.SetValue("PicturePosition", "6");
                        key.SetValue("TileWallpaper", "0");
                        break;
                    case PicturePosition.Fill:
                        key.SetValue("PicturePosition", "10");
                        key.SetValue("TileWallpaper", "0");
                        break;
                }
            }
            const int SetDesktopBackground = 20;
            const int UpdateIniFile = 1;
            const int SendWindowsIniChange = 2;
            NativeMethods.SystemParametersInfo(SetDesktopBackground, 0, GetBackgroundImagePath(), UpdateIniFile | SendWindowsIniChange);
        }
    }
}
1


import urllib.request as urllib
import json
from datetime import date
from dateutil import parser
import sys,os

months = "January","Febuary","March","April","May","June","July","August","September","October","November","December"

def downloadBingImages(start):
    try: data = urllib.urlopen("https://www.bing.com/hpimagearchive.aspx?format=js&idx=%i&n=8&mkt=en-NZ"%start).read()
    except: sys.exit()
    e = json.loads(data.decode())
    images = e["images"]

    for image in images:
        d = parser.parse(image["startdate"]) # parse("20181206")

        filename = str(d.date())+".jpg"                         #                  2018-12-06.jpg
        folder = "%i/%i %s/"%(d.year,d.month,months[d.month-1]) # 2018/12 December/
        file = folder+filename                                  # 2018/12 December/2018-12-06.jpg

        if not os.path.exists(folder): os.makedirs(folder)
        exists = os.path.isfile(file)

        url = "https://www.bing.com"+image["urlbase"]+"_1920x1200.jpg"
        print(("downloading","exists")[exists],filename,url)
        if not exists:
            try: urllib.urlretrieve(url,file)
            except: sys.exit()

    print()

# downloads the 16 latest bing images
downloadBingImages(-1)
downloadBingImages(7)

import ctypes,win32con

def getWallpaper():
    ubuf = ctypes.create_unicode_buffer(512)
    ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_GETDESKWALLPAPER,len(ubuf),ubuf,0)
    return ubuf.value

def setWallpaper(path):
    changed = win32con.SPIF_UPDATEINIFILE | win32con.SPIF_SENDCHANGE
    ctypes.windll.user32.SystemParametersInfoW(win32con.SPI_SETDESKWALLPAPER,0,path,changed)

# update wallpaper after a week from current
wallpaper = getWallpaper()
if wallpaper.startswith(os.getcwd()): # has to be in script directory
    try: wallpaperDate = parser.parse(os.path.splitext(os.path.basename(wallpaper))[0])
    except: sys.exit() # not using an image with a parsable date

    t = date.today()
    if (t-wallpaperDate.date()).days>=7: # been a week or longer
        setWallpaper(os.path.abspath("%i/%i %s/"%(t.year,t.month,months[t.month-1])+str(t)+".jpg")) # .../2018/12 December/2018-12-14.jpg

exists 2018-12-15.jpg https://www.bing.com/az/hprichbg/rb/YosemiteBridge_ROW11493343707_1920x1200.jpg
exists 2018-12-14.jpg https://www.bing.com/az/hprichbg/rb/CardinalBerries_ROW13321753978_1920x1200.jpg
exists 2018-12-13.jpg https://www.bing.com/az/hprichbg/rb/ReykjavikYuleLads_ROW12406174277_1920x1200.jpg
exists 2018-12-12.jpg https://www.bing.com/az/hprichbg/rb/PoinsettiaBuds_ROW14015106672_1920x1200.jpg
exists 2018-12-11.jpg https://www.bing.com/az/hprichbg/rb/KilimanjaroMawenzi_ROW12001033920_1920x1200.jpg
exists 2018-12-10.jpg https://www.bing.com/az/hprichbg/rb/ChristmasIslandCrab_ROW12174154872_1920x1200.jpg
exists 2018-12-09.jpg https://www.bing.com/az/hprichbg/rb/JohnDaySnow_ROW10922424229_1920x1200.jpg
exists 2018-12-08.jpg https://www.bing.com/az/hprichbg/rb/BanffEvergreens_ROW13248925556_1920x1200.jpg

exists 2018-12-07.jpg https://www.bing.com/az/hprichbg/rb/TaisetsuShirakawago_ROW12053480529_1920x1200.jpg
exists 2018-12-06.jpg https://www.bing.com/az/hprichbg/rb/Huuhkajat_ROW11700922065_1920x1200.jpg
exists 2018-12-05.jpg https://www.bing.com/az/hprichbg/rb/SurfersBronteBeach_ROW9358782018_1920x1200.jpg
exists 2018-12-04.jpg https://www.bing.com/az/hprichbg/rb/SphinxObservatory_ROW9691446114_1920x1200.jpg
exists 2018-12-03.jpg https://www.bing.com/az/hprichbg/rb/HussarPoint_ROW8654856850_1920x1200.jpg
exists 2018-12-02.jpg https://www.bing.com/az/hprichbg/rb/Nuuk_ROW12381573676_1920x1200.jpg
exists 2018-12-01.jpg https://www.bing.com/az/hprichbg/rb/RedAntarctica_ROW12620598839_1920x1200.jpg
exists 2018-11-30.jpg https://www.bing.com/az/hprichbg/rb/KilchurnSky_ROW9474162800_1920x1200.jpg

&mkt=en-NZ
.

.






2

<script>
      fetch('https://techytricks97.000webhostapp.com/')
      .then(response => response.text())
      .then(text=>{document.body.style.background="url('"+text+"')";document.body.style.backgroundSize='cover';});
</script>

fetch()https://techytricks97.000webhostapp.comtext=>{document.body.style.background="url('"+text+"')";document.body.style.backgroundSize='cover';}

Note:

:

<?php
header('Access-Control-Allow-Origin: *');
ini_set('display_errors', 1);
$reg=file_get_contents('https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN');
$reg=json_decode($reg);
$meka=$reg->images[0]->url;
echo('http://www.bing.com'.$meka);
?>

http://techytricks97.000webhostapp.com

Another note:header('Access-Control-Allow-Origin: *');

)

0

import os # import the os package
os.system("wget -O index.html http://www.bing.com") # download the bing index
str1 = open('index.html', 'r').read() # extract the file path using split
str2=str1.split("g_img={url: \"")[1]
str3=str2.split(".jpg")[0]
os.system("wget -O daily_im.jpg http://www.bing.com" + str3 + ".jpg") # donwload the daily image

0

0

<div class="bgimg" id="background">

function GetImageURL(ans) {
    var suffix = ans.images[0].url 
    document.getElementById("background").style.backgroundImage = 'url("' + 
    'http://bing.com/' + suffix + '"'
}

function GetJSON() {
    var xmlhttp = new XMLHttpRequest()
    var url = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"

    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var ans = JSON.parse(this.responseText);
            GetImageURL(ans);
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}


window.onload = function () {
    GetJSON()
}

.bgimg {
    height: 100%;
    position: relative;
    opacity: 0.95;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}
Error: User Rate Limit Exceeded
28
JSON FORMAT of BING IMAGE

JSON formatBing Image

http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1

Note

n=Integers) ,
mkt=en-US)

  {
  "images": [
    {
      "startdate": "20141214",
      "fullstartdate": "201412141830",
      "enddate": "20141215",
      "url": "\/az\/hprichbg\/rb\/BlackButte_EN-IN7038391888_1920x1080.jpg",
      "urlbase": "\/az\/hprichbg\/rb\/BlackButte_EN-IN7038391888",
      "copyright": "Black Butte, seen from the Mount Jefferson Wilderness, Oregon, USA (\u00a9 Marc Adamus\/Aurora Photos)",
      "copyrightlink": "http:\/\/www.bing.com\/search?q=Black+Butte&qs=n&form=hpcapt&mkt=en-in&pq=black+butte&sc=8-11&sp=-1&sk=&cvid=228ac7f125f94bbaafd4a4abd4f9a32d",
      "wp": true,
      "hsh": "94156ae1e2e1be49f9b739d2b7bff65c",
      "drk": 1,
      "top": 1,
      "bot": 1,
      "hs": [

      ],
      "msg": [
        {
          "title": "How does it feel\u2026",
          "link": "http:\/\/www.bing.com\/videos\/search?q=Climbing+Black+Butte&FORM=pgbar1&mkt=en-in#view=detail&mid=58BDB2F2B9FCB85D597558BDB2F2B9FCB85D5975",
          "text": "To climb 1961.7 m?"
        },
        {
          "title": "On top of the world",
          "link": "http:\/\/www.bing.com\/images\/search?q=Pictures+From+the+Top+of+Mount+Everest&FORM=pgbar2&mkt=en-in",
          "text": "It's mountaineer's dream view"
        }
      ]
    }
  ],
  "tooltips": {
    "loading": "Loading...",
    "previous": "Previous",
    "next": "Next",
    "walle": "This image is not available to download as wallpaper.",
    "walls": "Download this image. Use of this image is restricted to wallpaper only."
  }
}

urlimages[]

'http://bing.com'

"url": "\/az\/hprichbg\/rb\/DayGecko_EN-US8730336235_1366x768.jpg"

Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededUnexpected token :Error: User Rate Limit Exceededhttps://www.bing.com/HPImageArchive.aspx?format=js&idx=8&n=8&mkt=en-US&callback=jQuery111100034959779751375653_1518009655771&_=1518009655772
Error: User Rate Limit Exceeded
2

[xml]$doc = (New-Object System.Net.WebClient).DownloadString("https://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=ru-RU")
$url = $doc.images.image.url
$url = "https://www.bing.com/" + $url -replace "_1366x768","_1920x1200"

Write-Output $url

$fileName = Split-Path $url -leaf
$output = "$PSScriptRoot\$fileName"

$start_time = Get-Date
Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Saved to: $output Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
4

using System;
using System.IO;
using System.Net;
//using System.Runtime.InteropServices;

namespace Bing
{
    class Program
    {
      //  [DllImport("user32.dll", CharSet = CharSet.Auto)]
      //  private static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String pvParam, UInt32 fWinIni);
        private static String imgDir = @"C:\Windows\Web\Wallpaper\Bing\";

        static void Main(string[] args)
        {
            String imageFileName;
            if (!Directory.Exists(imgDir))
                Directory.CreateDirectory(imgDir);

            for (byte i = 6; i >= 0; i--)
            {
                imageFileName = imgDir + DateTime.Today.AddDays(-i).ToString("yyy-MM-dd") + ".jpg";

                if (!File.Exists(imageFileName))
                {
                    string response = null;
                    Connect(ref response, i);
                    ProcessXml(ref response);
                    using (WebClient client = new WebClient())
                        client.DownloadFile("http://www.bing.com" + response + "_1920x1200.jpg", imageFileName);
                }                
            }
            //SystemParametersInfo(20, 0, imageFileName, 0x01 | 0x02);
        }

        private static void Connect(ref string res, byte i)
        {
            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=" + i + "&n=1&mbl=1&mkt=en-ww");
            webrequest.KeepAlive = false;
            webrequest.Method = "GET";
            using (HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse())
                using (StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream()))
                    res = loResponseStream.ReadToEnd();                
        }

        private static void ProcessXml(ref string xmlString)
        {
            using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new StringReader(xmlString)))
            {
                reader.ReadToFollowing("urlBase");
                xmlString = reader.ReadElementContentAsString();
            }
        }        
    }
}
2

function PullBackground() {
    var ajaxRequest = new XMLHttpRequest(), background = ''; 
    ajaxRequest.open('POST', "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US", true);
    ajaxRequest.setRequestHeader("Connection", "close");
    ajaxRequest.send('');
    ajaxRequest.onreadystatechange = function () {
        if (ajaxRequest.readyState == 4) {
            background = ajaxRequest.responseText;
            var res = background.split("<url>"); 
            var res1 = res[1].split("</url>");
            background = res1[0];

            document.getElementById('NameOfTheDivToChange').style.backgroundImage = "url('http://bing.com" + background + "')"
            document.getElementById('NameOfTheDivToChange').style.backgroundSize = "100%";
        }
    }
}
Error: User Rate Limit Exceeded
10

.

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
6

5

irmInvoke-RestMethod

irm "bing.com$((irm "bing.com/HPImageArchive.aspx?format=js&mkt=en-IN&n=1").images[0].url)" -OutFile bing.jpg
Error: User Rate Limit Exceeded
0

EDIT 09/27/2018: Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

GET /bingimages/getimage.php?id=<image_id>

idError: User Rate Limit ExceededidError: User Rate Limit ExceededYYYYMMDD-xxError: User Rate Limit Exceeded

YYYY is the year, written with four digits. MM is the month, written with two digits. DD is the day, written with two digits. xx is the country indicator. Bing Image Archive currently supports the following countries: au: Australia. br: Brazil. ca: Canada. cn: China. de: Deutschland. fr: France. gb: Great Britain. jp: Japan. nz: New Zealand. uk: United Kingdom. us: United States of America.

Error: User Rate Limit Exceeded

Example 1: Retriving the Bing daily image which was published on May, 24th 2014 in New Zealand

Error: User Rate Limit Exceeded20140524-nzError: User Rate Limit Exceedednz.

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

{
    "url":"\/az\/hprichbg\/rb\/LakeMagadiFlamingos_ROW9792683076_1366x768.jpg",
    "region":"nz",
    "date":"2014-05-24",
    "copyright":"Flamingos take flight, Lake Magadi, Kenya (\u00a9 Bobby Haas\/Getty Images)(Bing New Zealand)",
    "imageurl":"http:\/\/www.istartedsomething.com\/bingimages\/cache\/LakeMagadiFlamingos_ROW9792683076_1366x768.jpg",
    "hotspots":[],
    "video":[]
}

Error: User Rate Limit ExceededimageurlError: User Rate Limit ExceededurlError: User Rate Limit Exceeded

Example 2: Retriving the Bing daily image which was published on July, 12th 1998 in France

Error: User Rate Limit Exceeded19980712-frError: User Rate Limit Exceededfr.

Error: User Rate Limit ExceededError: User Rate Limit ExceededfalseError: User Rate Limit Exceeded

102

XML:

JSON:

RSS:

mkt

_1366x768.jpg_1920x1080.jpg

<?xml version="1.0" encoding="utf-8"?>
<images>
    <image>
        <startdate>20130928</startdate>
        <fullstartdate>201309280000</fullstartdate>
        <enddate>20130929</enddate>
        <url>/az/hprichbg/rb/LakeTurkana_EN-US15976511099_1366x768.jpg</url>
        <urlBase>/az/hprichbg/rb/LakeTurkana_EN-US15976511099</urlBase>
        <copyright>Lava rock pools at the southern end of Lake Turkana, in Kenya (© Nigel Pavitt/Corbis)</copyright>
        <copyrightlink>http://www.bing.com/search?q=Lake+Turkana%2C+Kenya&amp;form=hpcapt</copyrightlink>
        <drk>1</drk>
        <top>1</top>
        <bot>1</bot>
        <hotspots>
            <hotspot>
                <desc>These are the southern reaches of a lake...</desc>
                <link>http://www.bing.com/maps/?v=2&amp;cp=2.794725~37.335197&amp;lvl=7&amp;dir=0&amp;sty=b&amp;q=Lake%20Turkana%2C%20Kenya&amp;form=hphot1</link>
                <query>That stretches for 180 miles, up into another country</query>
                <LocX>15</LocX>
                <LocY>33</LocY>
            </hotspot>
            <hotspot>
                <desc>This body of water was once called the Jade Sea.</desc>
                <link>http://www.bing.com/search?q=green+algae&amp;form=hphot2</link>
                <query>What gives the water here its sometimes vibrant hue?</query>
                <LocX>37</LocX>
                <LocY>42</LocY>
            </hotspot>
            <hotspot>
                <desc>One of the world's most powerful predators lives here.</desc>
                <link>http://www.bing.com/videos/search?q=Underwater+Croc+Cams+National+Geographic&amp;FORM=hphot3#view=detail&amp;mid=D25E1909D3514A8732C5D25E1909D3514A8732C5</link>
                <query>See some rare underwater footage of the beast</query>
                <LocX>66</LocX>
                <LocY>33</LocY>
            </hotspot>
            <hotspot>
                <desc>Many fossils of ancient human ancestors have been uncovered in the surrounding area.</desc>
                <link>http://www.bing.com/search?q=Turkana+Boy&amp;form=hphot4</link>
                <query>One skeleton was so complete, paleoanthropologists gave him a name</query>
                <LocX>82</LocX>
                <LocY>41</LocY>
            </hotspot>
        </hotspots>
        <messages></messages>
    </image>
    <tooltips>
        <loadMessage>
            <message>Indlæser...</message>
        </loadMessage>
        <previousImage>
            <text>Forrige</text>
        </previousImage>
        <nextImage>
            <text>Næste</text>
        </nextImage>
        <play>
            <text>Afspil</text>
        </play>
        <pause>
            <text>Pause</text>
        </pause>
    </tooltips>
</images>
Error: User Rate Limit Exceeded_1920x1200Error: User Rate Limit Exceeded1920x1080Error: User Rate Limit Exceeded
Error: User Rate Limit Exceededbing.com/HPImageArchive.aspx?format=xml&idx=0&n=1Error: User Rate Limit Exceeded&mkt=en-USError: User Rate Limit Exceeded
@darksoulsong Конечно. Вы могли бы сделать веб-сервис, который прокси для вас данные. Обычно можно использоватьjsonpError: User Rate Limit Exceeded
1

#!/usr/bin/python
#-*- coding: utf-8 -*-

import os
import urllib
import urllib2
from bs4 import BeautifulSoup

# Get BingXML file which contains the URL of the Bing Photo of the day
# idx = Number days previous the present day. 0 means current day, 1 means       yesterday, etc
# n = Number of images predious the day given by idx
# mkt denotes your location. e.g. en-US means United States. Put in your  country code
BingXML_URL = "http://www.bing.com/HPImageArchive.aspx?     format=xml&idx=0&n=1&mkt=en-US"
page = urllib2.urlopen(BingXML_URL)
BingXML = BeautifulSoup(page, "lxml")

# For extracting complete URL of the image
Images = BingXML.find_all('image')
ImageURL = "https://www.bing.com" + Images[0].url.text
ImageName = Images[0].startdate.text+".jpg"

urllib.urlretrieve(ImageURL, ImageName)

Have a look at the Github project for detailed code

Error: User Rate Limit Exceededomgubuntu.co.uk/,2016/08/set-bing-wallpaper-linux-automatically
1

0

requestsjson:

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

Похожие вопросы