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

Time:01-25

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')

I get the error code:

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

The HTML code:

<a  href="/u/abcd" rel="">@abcd</a>
<div >abcd</div>
    

CodePudding user response:

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')
  • Related