10

Working code 1:

Driver.Instance.FindElement( By.XPath("//a[contains(@href,'" + PartialLinkHref + "')]" ));

Working code 2:

ReadOnlyCollection<IWebElement> linkList = Driver.Instance.FindElements(By.TagName("a"));
for (int i = 0; i < linkList.Count ; i++)
{
     if (linkList[1].GetAttribute("href").Contains(PartialLinkHref))
     {
          element.SetElement(linkList[i]);
          return element;
          break;
     }
}
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
  • What is `PartialLinkHref`? – SiKing Feb 17 '15 at 23:50
  • 1
    I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Feb 18 '15 at 00:03

2 Answers2

9

The problem with your initial selector is that you're missing the // in front of the selector. the // tells XPath to search the whole html tree.

This should do the trick:

Driver.Instance.FindElement(By.XPath("//a[contains(@href, 'long')]"))

If you want to find children of an element, use .// instead, e.g.

var element = Driver.Instance.FindElement("..some selector..")
var link = element.FindElement(".//a[contains(@href, 'long')]"))

If you want to find a link that contains text and not by the href attribute, you can use

Driver.Instance.FindElement(By.XPath("//a[contains(text(), 'long')]"))
gaiazov
  • 1,908
  • 14
  • 26
1

I don't think the problem is your selector, I think it's the object you're trying to return the results of FindElements to.

In c#, FindElements returns a ReadOnlyCollection<IWebElement> object, not a List object. If you change your linkList definition, it should work:

ReadOnlyCollection<IWebElement> linkList = Driver.Instance.FindElements(By.TagName("a"));

You may also need to add this using:

using System.Collections.ObjectModel;
Richard
  • 8,961
  • 3
  • 38
  • 47