Posted By

ksaver on 02/28/11


Tagged

random fortune wikipedia


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ksaver


wikifortune.py


 / Published in: Python
 

Get a random page from Wikipedia.org and print text paragraph (fortune-like).

  1. #! /usr/bin/env python
  2. #
  3. # wikifortune.py
  4. # Get a random page (fortune-like) from Wikipedia.org
  5. # ksaver at identi.ca, Feb 2011.
  6. # Public Domain Code.
  7. #
  8.  
  9. import sys
  10. import urllib2
  11. from BeautifulSoup import BeautifulSoup, NavigableString
  12.  
  13. lang = 'en'
  14. url = 'http://%s.wikipedia.org/wiki/Special:Random' % lang
  15.  
  16. def getHtmlPage(url):
  17. useragent = 'Opera/11.01 (X11; FreeBSD 8.3-RELEASE i386; U; en)\
  18. Presto/2.6.62 Version/11.01'
  19. header = {'User-Agent': useragent}
  20. request = urllib2.Request(url, None, header)
  21. htmlpage = urllib2.urlopen(request)
  22. return (htmlpage.url, htmlpage.read())
  23.  
  24. def printText(tags):
  25. for tag in tags:
  26. if tag.__class__ == NavigableString:
  27. print tag.encode('Utf-8'),
  28. else:
  29. printText(tag)
  30. def main():
  31. pageurl, htmlpage = getHtmlPage(url)
  32. soup = BeautifulSoup(htmlpage)
  33.  
  34. paragraph = soup('p')[0]
  35. printText(paragraph)
  36. print '%s' % (pageurl)
  37.  
  38. if __name__ == '__main__':
  39. main()

Report this snippet  

You need to login to post a comment.