简体   繁体   中英

why does selenium change the element's href?

I'm using selenium to inspect a web element and then get its "href"

driver.findElement(getSelectorForButton(name)).getAttribute("href")

why the result I get is ...current url...# instead of jut # as I see in the browser console?

<a class="action-btn big-button btn-phone take-button v3" data-model="{&quot;analytics_url&quot;:&quot;/coupons/use?action_source=popup&amp;cookie=..uot;],&quot;redirect_url&quot;:null}" href="#">
    <div class="btn-text">
        <span>Call Now</span>
    </div>
</a>

I may be wrong but I think it is because

driver.findElement(getSelectorForButton(name));

does not return the DOM element, but a selenium wrapper which getAttribute property (method) invoked with the ('href') argument does not return the href attribute content, but the href property content.

The href property is 'filled' by the browser automatically with the matching prefix for every relative/absolute path in href.

Examples below:

HTML:

<a href="#" id="link1">Test</a>
<a href="./uri" id="link2">Test</a>
<a href="/uri" id="link3">Test</a>

JavaScript:

var a = document.getElementById('link1');
console.log(a.href); // '...Whatever_your_url_is...#'
console.log(a.getAttribute('href')); // '#'

var b = document.getElementById('link2');
console.log(b.href); // '...Whatever_your_url_is.../uri'
console.log(b.getAttribute('href')); // '/uri'

var c = document.getElementById('link3');
console.log(c.href); // '...Whatever_your_domain_and_port_is.../uri'
console.log(c.getAttribute('href')); // './uri'

DEMO here: http://jsfiddle.net/j8t470uk/

The reason is (as per docs)

this method will return the value of the given attribute, unless that attribute is not present, in which case the value of the property with the same name is returned (for example for the "value" property of a textarea element). If neither value is set, null is returned.

getAttribute first of all looks for the attribute in the DOM , where if you can see href contains the complete web url.

For example: in the answers you are getting on this question if you inspect the active tab you could see href="/questions/28339297/why-does-selenium-change-the-elements-href?answertab=active#tab-top" , but if you have a look at the DOM there you can find this href is appended to http://stackoerflow.com .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM