DanSmith
DanSmith

Reputation: 13

Fetching href element only from the element XPath in Selenium + Python

The application I am testing searches for an account based on the email ID. The email ID is unique. The result gets displayed in the form of a table with various columns. One of which is "Account Name" displaying the name of the user/account holder linked to the email address in question. In order to go into the account, one has to click on this "Account Name" value which is a link. This "Account Name" link is dynamic based on the email ID we use every time. On inspecting this link I get this:

<a href="/001m000000pFY6U?srPos=0&amp;srKp=001" data-seclke="Account" data-seclkh="60761f49cf4ed8788252c560b733bef0" data- seclki="001m000000pFY6U" data-seclkp="/001m000000pFY6U" data-seclkr="1" onmousedown="searchResultClick.mousedown(this, event)" xpath="1" style="">F John</a>

I am wondering if there is a way to retrieve/extract only the href="/001m000000pFY6U?srPos=0&amp;srKp=001" bit from the above.

I tried the following:

elem = self.driver.find_elements_by_xpath("//a[@href]")
print(elem)

and this prints 120 lines something similar to the following: selenium.webdriver.remote.webelement.WebElement (session="502b43c903be36c997d4882f26f3c7ad",element="0.4252537892711272- 1")

Would appreciate a little help. Thanks.

Upvotes: 1

Views: 232

Answers (4)

Ratmir Asanov
Ratmir Asanov

Reputation: 6459

Try the following line of code:

account_links = [link.get_attribute("href") for link in driver.find_elements_by_css_selector("a[data-seclke='Account']")]

where account_links will be a list of your needed links.

Hope it helps you!

Upvotes: 1

KunduK
KunduK

Reputation: 33384

Please try this code.Check if works

  shref=driver.find_element_by_xpath('//a[@data-seclke="Account"]').get_attribute("href")
    print(shref)

Upvotes: 0

Ali
Ali

Reputation: 1689

Try the below code :

elements = driver.find_elements_by_xpath("//a")
for i in elements:
    print i.get_attribute('href')

'a' will identify all the anchors then by using the attribute 'href', we can get the links.

Upvotes: 0

Moshe Slavin
Moshe Slavin

Reputation: 5204

You should use get_attribute.

For example:

elems = self.driver.find_elements_by_xpath("//a[@href]")
for i in elems:
     print(i.get_attribute("href")

Hope this helps you!

Upvotes: 0

Related Questions