You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
988B

  1. #!/usr/bin/python3
  2. import requests
  3. import sys
  4. import textwrap
  5. def connection_error():
  6. print("Could not contact wikipedia servers.")
  7. sys.exit(1)
  8. def get_random_page():
  9. params = {
  10. 'action' : 'query',
  11. 'format' : 'json',
  12. 'list' : 'random',
  13. 'rnlimit' : 1,
  14. 'rnnamespace' : 0
  15. }
  16. try:
  17. return requests.get('https://en.wikipedia.org/w/api.php', params).json()['query']['random'][0]
  18. except ConnectionError:
  19. connection_error()
  20. def get_page_with_summary(title):
  21. try:
  22. return requests.get('https://en.wikipedia.org/api/rest_v1/page/summary/' + title).json()
  23. except ConnectionError:
  24. connection_error()
  25. def main():
  26. while True:
  27. page = get_page_with_summary(get_random_page()['title'])
  28. if page['type'] == 'standard':
  29. break
  30. print(page['title'] + ':\n\n' + textwrap.fill(page['extract'], width=80))
  31. if __name__ == '__main__':
  32. main()