Advertisement
Guest User

Untitled

a guest
Aug 28th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. # Testing API requests here
  2.  
  3. import requests  # Web scraping/API access module
  4.  
  5. """
  6.  
  7. Used API - https://random-d.uk/api?format=json
  8.  
  9. Returning Random Duck photo
  10.  
  11. Both links use Version 2:
  12. https://random-d.uk/api
  13. https://random-d.uk/api/v2
  14.  
  15. """
  16.  
  17. """Below request pulls a duck photo link from the Random Duck API
  18.  'URL' contains random duck image
  19.  'Response' collects data from URL
  20.   response.json() asks for json format of data from link, creating usable dictionary
  21.   'duck_photo_link' Specifies dict key (url), which will pull dict value (Random duck photo URL)"""
  22.  
  23. # Grabs random duck photo or gif, converts to JSON dict format, then pulls the link by singling out the key ('url')
  24. URL = 'https://random-d.uk/api/random'
  25. response = requests.get(URL)
  26. duck_photo_link = response.json()["url"]
  27. print(duck_photo_link)
  28.  
  29. # Creates extension variable for .jpg or .gif photos
  30. if duck_photo_link[-4][-1] == "jpg":
  31.     extension = '.jpg'
  32. else:
  33.     extension = '.gif'
  34.  
  35. # Asks user to name file, attaches extension
  36. filename_input = input("Name your file: ")
  37. duck_filename = filename_input + extension
  38.  
  39. # Downloads duck photo to computer using requests module
  40. scraped_image = requests.get(duck_photo_link)
  41.  
  42. with open(duck_filename, 'wb') as f:
  43.     f.write(scraped_image.content)
  44.  
  45. # This puts photo in same location as the .py file is located, fix later
  46.  
  47. print("Download Successful:", duck_filename)
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement