Michel
Michel

Reputation: 23615

How can i select this span element?

I am just starting with Selenium and now in need to select this element:

<span class=" close">Matrices</span>

This line of code returns zero elements, so i guess it's not the right one :-)

ReadOnlyCollection<IWebElement> matrixLink = driver.FindElements(By.PartialLinkText("Matrices"));

But I could not find another one suitable, besides the Xpath, but that looks like this (//*[@id=\"Navigation\"]/div[2]/div[2]/ul/li[7]/span), and that seems a bit fragile to me?

EDIT: the span has the class 'close'. It's part of a menu, where there are 19 span's with the class 'close' so it's not a unique selector unfortunately....

Upvotes: 5

Views: 43683

Answers (3)

Virendra Joshi
Virendra Joshi

Reputation: 479

You can use //span[text()='Matrices'] It will select your element.

Upvotes: 2

Arran
Arran

Reputation: 25056

This will work:

//*[@id=\"Navigation\"]/descendant::span[text()='Matrices']

Note that if you can, be specific in your XPath queries, mainly to aid readability and improve performance...that is the * in your query will query all elements in the page. I don't know what kind of element the Navigation element is, but you should put it's exact element type in, for instance if it's a div, make it:

//div[@id=\"Navigation\"]/descendant::span[text()='Matrices']

A slight explanation for this XPath is that it will grab the Navigation element, and simply look anywhere inside it to find a span element that has the text of Matrices. Without the descendant bit in the XPath, it would only search for direct children. That means elements that a child of Navigation, nothing else - so if an element is a child of TestDiv which is a child of Navigation, descendant would catch it, without it you won't return any results.

As for why By.PartialLinkText would not work, this would only search for anchor links. It is common, as you have seen, that anchor links have a span element inside them or sometimes it is just a span on it's own.

By.PartialLinkText and similarly By.LinkText would not 'see' this element, since it's not an anchor element.

Upvotes: 8

Pavel Janicek
Pavel Janicek

Reputation: 14738

My favorite problem solver for these cases:

  • Install Selenium IDE
  • Click the link you need
  • In the "target" in Selenium IDE you will see different xpath possibilities

But I would use the approach, that its N-th element with "close" class (//span[7] or something like that)

Upvotes: 2

Related Questions