Skip to content

Instantly share code, notes, and snippets.

@prehensile
Last active December 19, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prehensile/5926461 to your computer and use it in GitHub Desktop.
Save prehensile/5926461 to your computer and use it in GitHub Desktop.
Fetch a random image referenced by Bing News RSS thumbnails.
import urlparse
import urllib2
import BeautifulSoup as Soup
import random
class BingSource:
def __init__( self ):
self.rss_url = "http://www.bing.com/news/?format=RSS"
def get_image_url( self ):
image_url = None
# fetch RSS data, parse into BeatifulSoup
h = urllib2.urlopen( self.rss_url )
soup = Soup.BeautifulStoneSoup( h.read() )
# iterate over items in feed
items = soup.findAll( "item" )
item = None
safety = len( items )
while (image_url is None) and (safety > 0):
# pick a random item
item = random.choice( items )
if item:
# check item has an image node
image_node = item.find("news:image")
if image_node:
# get query section of image node url
query = urlparse.urlparse( image_node.string )[4]
# urldecode the field named 'q' in the querystring
q = urlparse.parse_qs( query )["q"]
# set image_url
image_url = q[0]
safety -= 1
return image_url
if __name__ == '__main__':
url_source = BingSource()
print url_source.get_image_url()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment