You can download this code by clicking the button below.
This code is now available for download.
This function fetches a resource from a given URL and returns JSON, HTML, or plain text based on the response's Content-Type.
Technology Stack : requests, BeautifulSoup
Code Type : Function
Code Difficulty : Intermediate
import requests
import random
def fetch_random_resource(url):
response = requests.get(url)
content_type = response.headers.get('Content-Type')
if 'json' in content_type:
return response.json()
elif 'html' in content_type:
from bs4 import BeautifulSoup
return BeautifulSoup(response.content, 'html.parser').text
else:
return response.text
# JSON response