Last modified: Nov 04, 2023 By Alexander Williams

BeautifulSoup Find Stylesheets in HTML or Web

Example 1: Finding All Stylesheets in an HTML Document


# Parse the HTML content with Beautiful Soup
soup = BeautifulSoup(html_content, 'html.parser')

# Find all stylesheet links
stylesheets = soup.find_all('link', rel='stylesheet')

# Print the href attributes of found stylesheets
for stylesheet in stylesheets:
    print("Stylesheet: ", stylesheet['href'])

Output:


Stylesheet:  style.css
Stylesheet:  custom.css
Stylesheet:  print.css

Example 2: Finding Specific Stylesheets (e.g., Print Styles)


# Find specific stylesheets (e.g., print styles)
print_stylesheets = soup.find_all('link', rel='stylesheet', media='print')

# Print the href attributes of found print stylesheets
for stylesheet in print_stylesheets:
    print("Print Stylesheet: ", stylesheet['href'])

Output:


Print Stylesheet:  print.css

Example 3: Extracting Stylesheet URLs from a Web Page


import requests

# Send an HTTP request to a web page
url = "https://example.com"
response = requests.get(url)

# Parse the page content with Beautiful Soup
page_content = response.text
page_soup = BeautifulSoup(page_content, 'html.parser')

# Find all stylesheet links
page_stylesheets = page_soup.find_all('link', rel='stylesheet')

# Print the href attributes of found stylesheets
for stylesheet in page_stylesheets:
    print("Stylesheet URL: ", stylesheet['href'])

Output (URLs may vary depending on the web page):


Stylesheet URL:  /css/style.css
Stylesheet URL:  /css/custom.css