Open In App

Extract CSS tag from a given HTML using Python

Prerequisite: Implementing Web Scraping in Python with BeautifulSoup

In this article, we are going to see how to extract CSS from an HTML document or URL using python.



 Module Needed:

pip install bs4
pip install requests

Approach:



Implementation:




# import module
from bs4 import BeautifulSoup
  
# Html doc
html_doc = """
<html>
<head>
<title>Geeks</title>
</head>
<body>
<h2>paragraphs</h2>
  
<p>Welcome geeks.</p>
  
  
<p>Hello geeks.</p>
  
<a class="example" href="www.geeksforgeeks.com" id="dsx_23">java</a>
<a class="example" href="www.geeksforgeeks.com/python"  id="sdcsdsdf">python</a>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, "lxml")
  
# traverse CSS from soup
print("display by CSS class:")
print(soup.select(".example"))

Output:

display by CSS class:
[<a class="example" href="www.geeksforgeeks.com" id="dsx_23">java</a>, 
<a class="example" href="www.geeksforgeeks.com/python" id="sdcsdsdf">python</a>]

Now let’s get the CSS tag with URL:




# import module
from bs4 import BeautifulSoup
import requests
  
# link for extract html data
# Making a GET request 
      
def getdata(url):
    r=requests.get(url)
    return r.text
html_doc = getdata('https://www.geeksforgeeks.org/')
soup = BeautifulSoup(html_doc,"lxml")
  
# traverse CSS from soup
  
print("\nTags by CSS class:")
print(soup.select(".header-main__wrapper"))

Output:


Article Tags :