in this article, I'd like to share with you how to get Href of an element or multi-elements

1. Getting and Element href

Syntax


a.get('href')

Example


from bs4 import BeautifulSoup

html_source = 
'''
    <div>
       <a href="https://pytutorial.com"><p>Converting File Size in Python</p></a>
    </div>   
'''

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

# <a> element
print(print(soup.a.get("href")))

output


https://pytutorial.com

Getting all <a> elements href

Let's say you want to get all <a> element with tier tags, in the following example going to understand how to do that.

Example


from bs4 import BeautifulSoup

html_source = '''
    <div>
       <a href="https://pytutorial1.com"><p>Converting File Size in Python</p></a>
       <a href="https://pytutorial2.com"><p>Converting File Size in Python</p></a>
       <a href="https://pytutorial3.com"><p>Converting File Size in Python</p></a>
       <a href="https://pytutorial4.com"><p>Converting File Size in Python</p></a>
       <a href="https://pytutorial5.com"><p>Converting File Size in Python</p></a>
    </div>   
'''

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

#find all <a>
findall = soup.find_all('a')   

# print <a> href one by one
for i in findall:
    print(i.get('href'))

output


https://pytutorial2.com                                                                                                               
https://pytutorial3.com                                                                                                               
https://pytutorial4.com                                                                                                               
https://pytutorial5.com

First, we have found all <a> elements, then iterate over the result finally, got Href of <a> element.

English today is not an art to be mastered it's just a tool to use to get a result