Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: How to find element by partial href?

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;
     }
}
like image 674
Andrew Avatar asked Feb 17 '15 23:02

Andrew


People also ask

How do I find the partial text of an element?

The Java Syntax for locating a web element through its Partial Link Text is written as: driver. findElement(By. partialLinkText (<linktext>))

What is the difference between linkText and partial link text?

The link text locator matches the text inside the anchor tag. The partial link text locator matches the text inside the anchor tag partially. NoSuchElementException shall be thrown for both these locators if there is no matching element.

How do you take partial xpath?

With the xpath expression, we can use the contains() method and perform a partial match with the id. The xpath value shall be //*[contains(@id, 'id')]. This means the subtext id is present in the actual text gsc-i-id1. . We can also use the starts-with() and perform a match with the id.


2 Answers

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')]"))
like image 61
gaiazov Avatar answered Sep 27 '22 19:09

gaiazov


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;
like image 42
Richard Avatar answered Sep 27 '22 20:09

Richard