Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get the href in a <a class in Python Selenium?

I am trying to get a href from a webpage with selenium. When I use the browser console with following javascript command I get the right href:
document.getElementsByClassName('item-panel__title')[0].getAttribute('href')

Using Selenium trying to do the same, looking like this:

handle_browser.find_elements(By.CLASS_NAME,'item-panel__title')[0].getattr('href')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I get the error code:

AttributeError: 'WebElement' object has no attribute 'getattr'

The HTML code:

<a class="item-panel__title" href="/u/abcd" rel="">@abcd</a>
<div class="item-panel__description">abcd</div>
    

>Solution :

Getting web element attribute value with Selenium in Python is done with get_attribute() method.
So, instead of handle_browser.find_elements(By.CLASS_NAME,'item-panel__title')[0].getattr('href')
try using

handle_browser.find_elements(By.CLASS_NAME,'item-panel__title')[0].get_attribute('href')

Also, since you are getting from the first element in the list of possible matchings, you can use find_element instead of find_elements, as following:

handle_browser.find_element(By.CLASS_NAME,'item-panel__title').get_attribute('href')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading