Record#
- Today I learned how to use the request library to retrieve and process JSON data.
- Use
request.get("http***")
to retrieve data. - Use
result.json
to format the retrieved data as JSON. print(json.dumps(user, indent=2))
to print the JSON data in a more readable way.- Use
result.status_code
to get the request status code, such as 200. - Today's exercise is to retrieve 10 user information from
randomuser.me/api/
, save the avatars locally, and rename them with their names.
CODE#
main.py#
import requests, json
i = 0
for i in range(10):
result = requests.get("https://randomuser.me/api/")
user = result.json()
#print(json.dumps(user, indent=2))
name = f"""{user['results'][0]["name"]["first"]} {user['results'][0]["name"]["last"]}.jpg"""
image = user['results'][0]["picture"]["medium"]
picture = requests.get(image)
f = open(name, "wb")
f.write(picture.content)
f.close
print(f"{i} success")