Search code examples
pythonseleniumselenium-webdriverlinktextpartiallinktext

python selenium find_element_by_link_text, element exists but not found


I'm trying to click this link using selenium in python:

<header class="row package-collapse">
    <h5 ng-bind="ctrl.getPackageHeader(package)" class="ng-binding">Package "1" - not yet downloaded</h5>
    <!-- ngIf: package.DownloadedAt -->
</header>

After trying many different alternatives, I have finally managed to accomplish this by iterating through links until I find the right text, like this:

list = browser.find_elements_by_tag_name("h5")
for item in list:
    text = item.text
    if text == 'Package "1" - not yet downloaded':
        item.click()

OK, so, it works. But why on earth should I get an "unable to locate element" error if I just try the obvious solution:

browser.find_element_by_link_text('Package "1" - not yet downloaded')

It's right there and I'm looking at it, so I just don't get what I'm doing wrong. I've also tried using partial link text to search for it without the "1", using single or double quotes, but I still get "unable to locate element." There are no frames, no new windows opening or anything.

And yes, I'm posting this because I'm a novice and have no clue what I'm doing, so no need to belabor that particular point, thanks. :)


Solution

  • That's because by_link_text works only on <a> tags. For other tags you can use xpath

    Exact match

    find_element_by_xpath("//h5[.='Package \"1\" - not yet downloaded']")
    

    And for partial text

    find_element_by_xpath("//h5[contains(., '\"1\" - not yet downloaded')]")