如何选择该跨度元素? [英] How can i select this span element?
问题描述
我只是从Selenium开始,现在需要选择此元素:
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"));
但是,除了Xpath之外,我找不到另一个合适的,但看起来像这样(//*[@id=\"Navigation\"]/div[2]/div[2]/ul/li[7]/span
),对我来说似乎有点脆弱?
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?
编辑: 该范围具有关闭"类. 它是菜单的一部分,其中有19个跨度为'close'的类,因此很遗憾,它不是唯一的选择器....
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....
推荐答案
这将起作用:
//*[@id=\"Navigation\"]/descendant::span[text()='Matrices']
请注意,如果可以的话,请在您的XPath查询中进行具体说明,主要是为了提高可读性和提高性能...这就是查询中的*
将查询页面中的 all 元素.我不知道 Navigation 元素是哪种元素,但是您应该输入确切的元素类型,例如,如果它是div,则将其设置为
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']
对此XPath的一个简短解释是,它将捕获Navigation
元素,并且只需在其中的任何地方查找 即可找到文本为Matrices
的span
元素.如果没有XPath中的descendant
位,它将仅搜索直接子级.这意味着元素是Navigation
的子元素,别无其他-因此,如果元素是TestDiv
的子元素,而TestDiv
是Navigation
的子元素,则descendant
会捕获它,如果没有它,您将不会返回任何结果
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.
关于为什么By.PartialLinkText
不起作用的原因,这只会搜索锚链接.如您所见,锚链接内部通常有一个span
元素,有时它本身只是一个span
.
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
和类似的By.LinkText
不会看到"该元素,因为它不是锚元素.
By.PartialLinkText
and similarly By.LinkText
would not 'see' this element, since it's not an anchor element.
这篇关于如何选择该跨度元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!