无法在Selenium中获得第n个节点

cul*_*rón 16 selenium xpath css-selectors

我尝试编写xpath表达式,以便我的测试不会被小的设计更改破坏.因此,不是Selenium IDE生成的表达式,而是编写自己的表达式.

这是一个问题:

//input[@name='question'][7]
Run Code Online (Sandbox Code Playgroud)

这个表达式根本不起作用.名为"问题"的输入节点分布在整个页面上.他们不是兄弟姐妹.

我尝试过使用中间表达式,但也失败了.

(//input[@name='question'])[2]
error = Error: Element (//input[@name='question'])[2] not found
Run Code Online (Sandbox Code Playgroud)

这就是为什么我认为Seleniun有一个错误的XPath实现.

根据XPath文档,位置谓词必须按节点集中的位置进行过滤,因此必须找到input带有名称的第七个'question'.在Selenium中,这不起作用.CSS选择器(:nth-of-kind)也没有.

我不得不写一个过滤他们共同父母的表达式:

//*[contains(@class, 'question_section')][7]//input[@name='question']
Run Code Online (Sandbox Code Playgroud)

这是一个特定的Selenium问题,还是我错误地阅读了规范?我该怎么做才能缩短表达方式?

Dim*_*hev 25

这是一个问题:

//input[@name='question'][7]   
Run Code Online (Sandbox Code Playgroud)

这个表达式根本不起作用.

这是一个FAQ.

[] has a higher priority than //.

The above expression selects every input element with @name = 'question', which is the 7th child of its parent -- and aparently the parents of input elements in the document that is not shown don't have so many input children.

Use (note the brackets):

(//input[@name='question'])[7]
Run Code Online (Sandbox Code Playgroud)

This selects the 7th element input in the document that satisfies the conditions in the predicate.

Edit:

People, who know Selenium (Dave Hunt) suggest that the above expression is written in Selenium as:

xpath=(//input[@name='question'])[7]
Run Code Online (Sandbox Code Playgroud)

  • 请注意,Selenium只会将定位符解释为XPath,如果它以`//`或`xpath =`开头,那么以`(``将默认尝试按标识符(`id`或`name`)定位元素). (6认同)
  • @ Dave-Hunt:那么,`xpath =(//输入[@ name ='question'])[7]`那么可以接受吗? (3认同)
  • 然后使用Dave Hunt的答案 - 这有更好的机会得到Selenium称之为"XPath"的支持. (2认同)

Dav*_*unt 6

如果您希望第7个inputname属性的值question在源代码中,请尝试以下操作:

/descendant::input[@name='question'][7]
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,但是'descendant-or-self`不是`descendant`的直接同义词.请参阅http://www.w3.org/TR/xpath/#path-abbrev"注意:位置路径`// para [1]`与位置路径`/ descendant :: para [1并不相同]`.后者选择第一个后代`para`元素;前者选择所有后代`para`元素,它们是父母的第一个'para`子元素." (2认同)
  • 正确答案(+1). (2认同)