Randomly Fetch and Display News Article

  • Share this:

Code introduction


The function fetches a list of news from a given URL, randomly selects an article, and returns the title and content of the article.


Technology Stack : Requests, BeautifulSoup

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import requests
from bs4 import BeautifulSoup

def fetch_random_news(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    news_list = soup.find_all('div', class_='news-item')
    if news_list:
        random_news = random.choice(news_list)
        title = random_news.find('h2').text
        content = random_news.find('p').text
        return {
            'title': title,
            'content': content
        }
    else:
        return "No news found."

# JSON Explanation