Search code examples
pythonseleniumselenium-webdriveronclickhref

Why can't I get the href attribute of an element where as I can click on it using Selenium


I see that many people have the reverse problem, but mine is this:

I have this webelement and when I use element.click() it redirects me to a website (the element has a link)

When I use element.get_attribute('href') I get None and I even tried to use a javascript to check for attributes of element, but it only has a class attribute.

Is there a way for me to get this link without clicking on the element?

From chrome inspection of elements in the webpage we have:

<div "element.class">
    <a href='link_that_i_want'>

Solution

  • href attribute

    The href attribute specifies the URL of the page the link goes to.

    Example:

    <a href="https://www.w3schools.com">Visit W3Schools</a>
    

    The href attribute can be used on the following elements:

    • <a>
    • <area>
    • <base>
    • <link>

    onclick event attribute

    The onclick event attribute executes a JavaScript when a button is clicked. The onclick attribute fires on a mouse click on the element.

    Example:

    <button onclick="myFunction()">Click me</button>
    

    Conclusion

    Possibly the desired element have the onclick attribute instead of the href attribute.