You can download this code by clicking the button below.
This code is now available for download.
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