62

Using Selenium and the Chrome Driver I do:

links = browser.find_elements_by_partial_link_text('##') matches about 160 links.

If I try,

for link in links:
    print link.text

with it I get the text of all the links:

##1
##2
...
##160

The links are like this:

<a href="1.html">##1</a>
<a href="2.html">##2</a>
...
<a href="160.html">##160</a>

How can I get the href attribute of all the links found?

Eduard Florinescu
  • 16,747
  • 28
  • 113
  • 179

2 Answers2

93

Call get_attribute on each of the links you have found:

links = browser.find_elements_by_partial_link_text('##')
for link in links:
    print(link.get_attribute("href"))
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Scott
  • 9,458
  • 7
  • 54
  • 81
  • 1
    I found that I needed to use: `link._element.get_attribute("href")`. (that was when making the request with: `browser.find_by_tag('a')` – toast38coza Jun 03 '16 at 12:26
2

An existing answer to a similar question seems like it might apply:

Assume

your HTML consists solely of that one tag, then this should do it:

String href = selenium.getAttribute("css=a@href");

You use the DefaultSelenium#getAttribute() method and pass in a CSS locator, an @ symbol, and the name of the attribute you want to fetch. In this case, you select the a and get its @href.

So if the link contains "..blablabla..." text then you can find it in that way:

selenium.getAttribute("css=a:contains('..blablabla...')@href");
Community
  • 1
  • 1
eugene.polschikov
  • 7,254
  • 2
  • 31
  • 44