You can download this code by clicking the button below.
This code is now available for download.
This function fetches a random quote from the quotable.io API and prints it out. It uses the requests library to send HTTP requests and extract the quote and author from the JSON response.
Technology Stack : Requests
Code Type : Function
Code Difficulty : Intermediate
import requests
import random
def get_random_user_agent():
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 UBrowser/44.0.2403.157 Safari/537.36"
]
return random.choice(user_agents)
def fetch_random_quote():
url = 'https://api.quotable.io/random'
headers = {
'User-Agent': get_random_user_agent()
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return None
def display_quote():
quote = fetch_random_quote()
if quote:
print(f"Quote: {quote['content']}")
print(f"Author: {quote['author']}")
else:
print("Failed to fetch a quote.")