Last modified: Jan 10, 2023 By Alexander Williams

How to Get href of Element using BeautifulSoup [Easily]

To get the href attribute of <a> tag, we need to use the following syntax:

tag['href']

By using the above syntax, we'll learn how to:

  • Get the href attribute of a tag
  • Get the href attribute of multi tags

Get the href attribute of a tag

In the following example, we'll use find() function to find <a> tag and ['href'] to print the href attribute.

from bs4 import BeautifulSoup # Import BeautifulSoup module

# 👇 HTML Source
html = '''
 <a href="/python/string">Python string</a> 
'''

soup = BeautifulSoup(html, 'html.parser') # 👉️ Parsing

a_tag = soup.find('a', href=True) # 👉️ Find <a> tag that have a href attr

print(a_tag['href']) # 👉️ Print href 

Output:

/python/string

href=True: the tags that have a href attribute.

Get the href attribute of multi tags

To get the href of multi tags, we need to use findall() function to find all <a> tags and ['href'] to print the href attribute. However, let's see an example.

from bs4 import BeautifulSoup # Import BeautifulSoup module

# 👇 HTML Source
html = '''
 <a href="/python/string">Python string</a> 
 <div>
 <a href="/python/variable">Python variable</a> 
 <a href="/python/list">Python list</a> 
 <a href="/python/set">Python set</a> 
 </div>
'''

soup = BeautifulSoup(html, 'html.parser') # 👉️ Parsing

a_tags = soup.find_all('a', href=True) # 👉️ Find all <a> tags that have a href attr

# 👇 Loop over the results
for tag in a_tags:
    print(tag['href']) # 👉️ Print href 

Output:

/python/string
/python/variable
/python/list
/python/set

Conclusion

Remember, when you want to get any attribute of a tag, use the following syntax:

tag[attribute name]

You can visit beautifulsoup attribute to learn more about the BeautifulSoup attribute. Also, for more BeautifulSoup topics, scroll down you will find it.