Random Quote Fetcher with BeautifulSoup

  • Share this:

Code introduction


This function fetches web content from a specified URL, parses the HTML using BeautifulSoup, and randomly selects a div element containing a quote, returning the text within it.


Technology Stack : Requests, BeautifulSoup

Code Type : Function

Code Difficulty : Intermediate


                
                    
import requests
import random
from bs4 import BeautifulSoup

def fetch_random_quote(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    quotes = soup.find_all('div', class_='quote')
    random_quote = random.choice(quotes)
    return random_quote.text