You can download this code by clicking the button below.
This code is now available for download.
This function takes a URL and a list of tags as arguments, and returns a random sample of 5 links from the given URL (if there are fewer than 5 links, it returns all of them).
Technology Stack : beautifulsoup4, requests, random
Code Type : Function
Code Difficulty : Intermediate
def find_random_links(url, tags):
from bs4 import BeautifulSoup
import requests
import random
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = []
for tag in tags:
for link in soup.find_all(tag):
links.append(link.get('href'))
return random.sample(links, min(len(links), 5))