Last modified: September 30, 2021

How to Get href of Element using BeautifulSoup [Easily]

In this article, we're going to learn how to get the href attribute of an element by using python BeautifulSoup.

1. Getting href attribute

syntax:


el['href']

Example


from bs4 import BeautifulSoup

# Html
html_source = '''
       <a href="https://ex.com/home">Converting File Size in Python</a> 
'''

# BeautifulSoup
soup = BeautifulSoup(html_source, 'html.parser')

# Find element which have href attr
el = soup.find(href=True)

# Print href value
print(el['href'])

Output:

https://ex.com/home

2. Get href from class

Example:


# Html
html_source = '''
       <a class="1" href="https://ex.com/home">Converting File Size in Python</a> 
'''


# BeautifulSoup
soup = BeautifulSoup(html_source, 'html.parser')

# Find element by class which have href attr
el = soup.find(class_='1', href=True)

# Print href value
print(el['href'])

Output:

https://ex.com/home