【问题标题】:Is there a way to get Bing's photo of the day?有没有办法获得 Bing 当天的照片?
【发布时间】:2012-05-17 16:44:57
【问题描述】:

有什么方法可以通过编程方式获取 Bing 背景图像吗?

Bing 的 API 似乎没有提供这样的功能,或许还有其他方法?

【问题讨论】:

    标签: bing


    【解决方案1】:

    我认为最好的方法是通过 AJAX 调用模仿他们自己的方式。

    他们调用这个 URL 并通过 XML 反序列化提取信息。

    XML: http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US

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

    RSS: http://www.bing.com/HPImageArchive.aspx?format=rss&idx=0&n=1&mkt=en-US

    mkt 属性显然可以更改为与“en-US”不同的区域,但如果您不关心特定区域,也可以完全退出。

    请注意,添加到图像名称的_1366x768.jpg 后缀似乎可以修改为不同的分辨率(例如_1920x1080.jpg 用于全高清和可能的其他分辨率)。

    这是截至 2013 年 9 月 28 日的 XML 格式数据转储。

    <?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>
    

    【讨论】:

    • 仅供参考 - 您也可以使用 JSON 格式获取它! bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
    • 顺便说一句:分辨率是可变的,_1920x1200 以内的任何东西都可以,即1920x1080 等也可以。
    • 好的,Bing Desktop 似乎使用了bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1,即没有&amp;mkt=en-US 部分。即使我将应用设置为“英语-美国”也是如此。
    • @darksoulsong 当然。您可以制作一个为您代理数据的网络服务。通常,人们会使用jsonp,但他们似乎不允许这样做。
    • 如果有人在寻找市场......你可以从microsoft.com/en-in/locale.aspx提取它
    【解决方案2】:

    BING 图像的 JSON 格式

    我找到了一种方法来获取当天 Bing 图像 的 JSON 格式

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

    注意

        n=你想要的图片数量(你可以使用整数),
    mkt=你的 位置(例如:en-US)


    这是 JSON 输出的样子
      {
      "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."
      }
    }
    

    使用images[]中的url

    并将其添加到'http://bing.com'

    这里的网址是"url": "\/az\/hprichbg\/rb\/DayGecko_EN-US8730336235_1366x768.jpg"

    【讨论】:

    • 看起来 Bing 将响应总数限制为一次 8 个。 8个可以通过n=8来收集,之前的8个可以通过设置idx=8和n=8来收集。我看不出有什么方法可以扩展它。
    • 为什么它在https://www.bing.com/HPImageArchive.aspx?format=js&amp;idx=8&amp;n=8&amp;mkt=en-US&amp;callback=jQuery111100034959779751375653_1518009655771&amp;_=1518009655772中给出错误Unexpected token :
    【解决方案3】:

    Microsoft 最近发布了适用于 Windows 7 的 Bing Dynamic Theme,其中包含 an RSS Feed with links to Bing wallpapers。

    还有一个 Python script 尝试加载 Bing 网站并猜测正确的图像 URL,但根据我的经验,它通常会导致图像分辨率低于 RSS 提要提供的图像。

    【讨论】:

    • +1 链接到 rss,我认为这是问题的实际答案
    • 不幸的是,该主题已停产,或者正如微软所说:“该主题已停用”。 RSS 仍然存在,但不再更新。
    【解决方案4】:

    单行 PowerShell(3.0 或更高版本)

    irm 是Invoke-RestMethod 的别名

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

    【讨论】:

    • 太棒了!非常适合我:)
    【解决方案5】:

    我迟到了,但如果有人需要 PHP 实现:我写了一个简单的类来处理这个过程:

    https://github.com/grubersjoe/bing-daily-photo

    【讨论】:

      【解决方案6】:

      我也喜欢 Bing 图片,但他们的应用程序过于臃肿,无法下载图片。在分析了与提琴手的联系后,我编写了这段代码。 1920x1200 带有嵌入的 Bing 徽标,但较低的分辨率没有它。

      您可以让 Windows 显示您设置的图像文件夹中的随机图像,因此当您每天下载它们时,它会显示更多随机图像。 如果您确实保留了“imageDir”,则需要更改该文件夹的权限,否则它会崩溃,我没有为捕捉错误而烦恼。 最后,如果您想将壁纸设置为今天的图像,请取消注释行,或者您可以创建一个任务来运行程序,比如登录后一分钟。

      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();
                  }
              }        
          }
      }
      

      【讨论】:

        【解决方案7】:

        我看到很多人也要求新的RSS链接,只需将URL中的格式参数更改为“rss”即可。

        RSS:http://www.bing.com/HPImageArchive.aspx?format=rss&idx=0&n=1&mkt=en-US

        【讨论】:

          【解决方案8】:

          此 JavaScript 将通过将 div 的背景图像更改为当天的 bing 图像的背景来回答“如何处理 api”。

          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%";
                  }
              }
          }
          

          【讨论】:

          • 我真的很想使用它,但它似乎无法解决 Bing 设置的“Access-Control-Allow-Origin”缺失问题。
          【解决方案9】:

          如果有人在寻找可能的实现,我用 C# 编写了一个小命令行程序来下载、保存并将我的背景设置为每日必应图像。随意修改它以适应您的个人需求。 https://github.com/josueespinosa/BingBackground

          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);
                  }
              }
          }
          

          【讨论】:

            【解决方案10】:

            在Github 上查看bing-desktop-wallpaper-changer。该脚本是用 python 编写的,我希望你能在那里找到答案。

            #!/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)
            

            查看 Github 项目以获取详细代码

            【讨论】:

            【解决方案11】:

            简单的 PowerShell,放入文件夹,在 Windows 任务计划程序中创建每日任务,脚本将图像保存在其运行文件夹中,然后在您的桌面背景设置中选择该文件夹作为背景。

            [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)"
            

            【讨论】:

            • 在 Windows 中作为计划任务更好地自动将当天的 Bing 图像下载到目标目录。很棒。
            【解决方案12】:

            这是一个简单的 Python 脚本,仅使用 requests 和 json 即可获取当天的必应照片:

            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 之类的文件写入执行脚本的同一目录中。当然,可以在这里调整一大堆东西,但可以相当容易地完成工作。

            【讨论】:

              【解决方案13】:

              Bash 一个班轮(需要 bash、curl 和 jq),对于放入 cronjob 很有用:

              BACKGROUND_META=$(curl 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US'); curl -o $(echo $BACKGROUND_META | jq -r '.images[0].urlbase' | sed s/.*=//).jpg "https://bing.com$(echo $BACKGROUND_META| jq -r '.images[0].url')"
              

              【讨论】:

                【解决方案14】:

                我无法获得可以与 John’s Background Switcher 一起使用的正确 RSS 提要,直到我发现这个 feedburner 提要似乎工作得很好:http://feeds.feedburner.com/bingimages

                【讨论】:

                  【解决方案15】:

                  我终于决定用 Python 3 编写一个脚本来从 xml 存档中获取最多的图像 (16)。

                  所以现在我可以毫不费力地归档图像。只需运行 Python 脚本。
                  我将图像组织到年/月文件夹中,如下所示:2018 > 12 月 12 日 > 2018-12-06.jpg

                  此脚本位于我的 Bing 壁纸文件夹中。 (在我的图片文件夹中)

                  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)
                  

                  用于更新壁纸的可选额外代码:(放在 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
                  

                  附:上面的脚本使用&amp;mkt=en-NZ 处理新西兰的图片。
                  您可以查看其他国家/地区的市场代码here。

                  您还可以查看自 2009 年以来为不同国家/地区存档的所有图片here。
                  (虽然仅在 1366x768 中)

                  主要附言将脚本添加到任务计划程序以在登录时运行。 (或每天/每周)

                  创建基本任务
                  程序/脚本:python(或 C:\Python34\python.exe,如果它不在您的环境路径中)
                  参数:“path/to/your/script.py”
                  开始于:“路径/到/你的”

                  更新! (2019 年 3 月)
                  2019 年 3 月 10 日的图像在 xml 和 rss 格式中的开始日期 (20190309) 均错误。
                  改为使用 Json 格式。 (因为它给出了准确的日期)

                  【讨论】:

                    【解决方案16】:

                    https://peapix.com/bing/feed 将列出最新的不带 Bing 标志的 Bing 图片,由peapix.com 维护。支持以下国家/地区:AU、CA、CN、DE、FR、JP、US、GB。

                    例如,https://peapix.com/bing/feed?country=jp 代表日本,https://peapix.com/bing/feed?country=us 代表美国。

                    【讨论】:

                      【解决方案17】:

                      OP 没有指定操作系统,所以这里有一个用于 Linux 的。我根据提供的脚本修改了here。

                      基本上它获取当天图片的url,下载图片并保存到固定文件~/.config/wallpaper.jpg,并使用feh设置壁纸。同时发送通知。

                      #!/bin/sh
                      
                      WP_FILE=$HOME/.config/wallpaper.jpg
                      
                      bing="www.bing.com"
                      
                      # $xmlURL is needed to get the xml data from which
                      # the relative URL for the Bing pic of the day is extracted
                      #
                      # The mkt parameter determines which Bing market you would like to
                      # obtain your images from.
                      # Valid values are: en-US, zh-CN, ja-JP, en-AU, en-UK, de-DE, en-NZ, en-CA or opted out.
                      #
                      # The idx parameter determines where to start from. 0 is the current day,
                      # 1 the previous day, etc.
                      xmlURL="http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US"
                      
                      # The desired Bing picture resolution to download
                      # Valid options: "_1024x768" "_1280x720" "_1366x768" "_1920x1200"
                      desiredPicRes="_1920x1080"
                      
                      # The file extension for the Bing pic
                      picExt=".jpg"
                      
                      # Extract the relative URL of the Bing pic of the day from
                      # the XML data retrieved from xmlURL, form the fully qualified
                      # URL for the pic of the day, and store it in $picURL
                      
                      # Form the URL for the desired pic resolution
                      desiredPicURL=$bing$(curl -s $xmlURL | grep -oP "(?<=<urlBase>)(.*?)(?=</urlBase>)")$desiredPicRes$picExt
                      
                      # Form the URL for the default pic resolution
                      defaultPicURL=$bing$(curl -s $xmlURL | grep -oP "(?<=<url>)(.*?)(?=</url>)")
                      
                      # $picName contains the filename of the Bing pic of the day
                      
                      # Attempt to download the desired image resolution. If it doesn't
                      # exist then download the default image resolution
                      if wget --quiet --spider "$desiredPicURL"
                      then
                      
                          # Download the Bing pic of the day at desired resolution
                          curl -s -o "$WP_FILE" "$desiredPicURL"
                      else
                          # Download the Bing pic of the day at default resolution
                          curl -s -o "$WP_FILE" "$defaultPicURL"
                      fi
                      
                      if [[ -f "${WP_FILE}" ]]; then
                          feh --bg-scale "$WP_FILE" && \
                              notify-send -i emblem-photos "Wallpaper" "Wallpaper changed" \
                              -h int:suppress-sound:1 -h int:transient:1
                      fi
                      

                      【讨论】:

                        【解决方案18】:

                        您可以考虑获取该 url 的 file_content 并在文件中搜索图像。 不确定这是最好的方法,但这是一种方法。

                        【讨论】:

                          【解决方案19】:

                          使用来自 @Siv 的 URL,这是一个更新 &lt;div class="bgimg" id="background"&gt; 的 JavaScript 示例

                          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()
                          }
                          

                          这个类的css是:

                          .bgimg {
                              height: 100%;
                              position: relative;
                              opacity: 0.95;
                              background-position: center;
                              background-repeat: no-repeat;
                              background-size: cover;
                          }
                          

                          【讨论】:

                          • 这对我不起作用,因为浏览器的同源策略...
                          【解决方案20】:

                          您可以在 linux 机器上使用 python 和 wget 做到这一点:

                          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
                          

                          它会下载本地目录中名为daily_im.jpg 的每日必应背景。您可以将所有内容放在 script.py 中并以编程方式启动它。

                          【讨论】:

                            【解决方案21】:

                            编辑 2018 年 9 月 27 日: http://www.istartedsomething.com/bingimages 响应 404 数周。它可能已经不存在了。 :-(

                            您可以使用 istartedsomething.com's Bing Image Archive。这是一个非官方的 Bing Image Archive。它使用自制端点,有助于检索图像:

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

                            id 是一个字符串,其中包含图像的发布日期和发布的国家/地区。 id 必须符合以下格式:YYYYMMDD-xx,其中:

                            • YYYY 是年份,用四位数字书写。
                            • MM 是月份,用两位数书写。
                            • DD 是日期,用两位数书写。
                            • xx 是国家指示符。 Bing Image Archive 目前支持以下国家:
                              • au: 澳大利亚。
                              • br: 巴西。
                              • ca: 加拿大。
                              • cn: 中国。
                              • de:德国。
                              • fr: 法国。
                              • gb: 英国。
                              • jp: 日本。
                              • nz: 新西兰。
                              • uk: 英国。
                              • us: 美利坚合众国。

                            如果它有一些信息,它会返回一个有用的 JSON 对象,如果它没有任何东西,它会返回 false。

                            示例 1: 检索 2014 年 5 月 24 日在新西兰发布的 Bing 每日图片

                            图片 ID 为 20140524-nz,因为所需图片发布于 2014 年 5 月 24 日,发布于新西兰,国家指标为 nz。

                            http://www.istartedsomething.com/bingimages/getimage.php?id=20140524-nz 返回以下 JSON 片段:

                            {
                                "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":[]
                            }
                            

                            您可以使用imageurl 字段或url(Bing URL 路径)字段来获取您的图片。

                            示例 2: 检索 1998 年 7 月 12 日在法国发布的 Bing 每日图片

                            图片 ID 为 19980712-fr,因为所需图片发布于 1998 年 7 月 12 日,发布于法国,国家指示符为 fr。

                            http://www.istartedsomething.com/bingimages/getimage.php?id=19980712-fr 返回false,因为在 1998 年 7 月 12 日没有法国的 Bing Daily Image(此时甚至不存在 Bing)。

                            【讨论】:

                            • 链接死了,我没有找到类似的更新答案。
                            猜你喜欢
                            • 2018-08-25
                            • 2012-07-30
                            • 2015-12-29
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2022-01-08
                            • 1970-01-01
                            相关资源
                            最近更新 更多