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....
For a given HTML document and the task is to get the text of a <span> tag using JQuery. you can Use jQuery text() method():This method is used to set or return the text content of specified elements.
The <span> HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang .
We can select the text of a span on click with Selenium webdriver. To identify the element with span tag, we have to first identify it with any of the locators like xpath, css, class name or tagname. After identification of the element, we can perform the click operation on it with the help of the click method.
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.
My favorite problem solver for these cases:
But I would use the approach, that its N-th element with "close" class (//span[7]
or something like that)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With