0

I found this code in here : Is there a way to get Bing's photo of the day?

I'm sorry I couldn't comment there so I'm asking here. but I have a few problems. when I run it in Debian, it says " list index out of range" I don't understand how to fix this. I'm sorry if that sounds dumb of me.

    #!/usr/bin/python3

from bs4 import BeautifulSoup
import os
import urllib
from urllib.request import urlopen

BingXML_URL ="http://www.bing.com/HPImageArchive.aspx?"
page= urlopen(BingXML_URL).read()
BingXml =BeautifulSoup(page, "lxml")
Images = BingXml.find_all('image')
ImageURL ="https://www.bing.com" + Images[0].url.text
ImageName = Images[0].startdate + ".jpg"

urllib.urlretrieve(ImageURL, ImageName)

1 Answers1

1

The link you are using is not the same as the one stated in the article. The article says the link is
https://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US
, but you used
http://www.bing.com/HPImageArchive.aspx?
which Bing does not respond to. Try this new link and see if it works.

Also, there are some more minor mistakes:

  1. urlretrieve is in urllib.request, not urllib, so using from urllib.request import urlopen, urlretrieve and urlretrieve(ImageURL, ImageName) might be better.
  2. Images[0].startdate is a Tag object, which cannot be added to a str ".jpg". You can use Images[0].startdate.get_text() to get the string and add with a str.

So the finished code should be:

#!/usr/bin/python3
from bs4 import BeautifulSoup
import os
import urllib
from urllib.request import urlopen, urlretrieve

BingXML_URL ="http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US"
page= urlopen(BingXML_URL).read()
BingXml =BeautifulSoup(page, "lxml")
Images = BingXml.find_all('image')
ImageURL ="https://www.bing.com" + Images[0].url.text
ImageName = Images[0].startdate.get_text() + ".jpg"

urlretrieve(ImageURL, ImageName)
David
  • 816
  • 1
  • 6
  • 16
  • Thank you so much. yes, I made mistake there. may I also ask how I can change the path of the image? I want to save it in my pictures and then autmaticly it appears on desktop background. I'm sorry for asking so many question. – shahrzad ar Dec 06 '20 at 09:19
  • 1
    Just change `urlretrieve(ImageURL, ImageName)`. The `ImageName` parameter is actually the file path. For example, change it to `'/home/yourname/Pictures/' + ImageName` would save it under your Pictures folder. – David Dec 06 '20 at 10:29
  • Thank you. I really appreciate it. how can I use os.path.expanduser('~') so that the path change for other users? – shahrzad ar Dec 06 '20 at 12:11
  • You can use `os.path.expanduser('~/Pictures/' + ImageName)` to save the image to the current user's Pictures folder. – David Dec 18 '20 at 12:12