如何在Selenium中使用xpath 'not'语句?



我正在使用硒来自动化一些测试用例,但是在寻找一些没有特定风格的元素时遇到了一些问题。我已经创建了这个在 Chrome 中完美运行的 Xpath,但是当我使用硒运行它时,它无法按我想要的方式工作。

通道:./td[not(contains(@style, 'foo'))]

所以基本上HTML看起来像这样:

<tr id='something'>
   <td style='foo'><td/>
   <td style='foo'><td/>
   <td style='foo'><td/>
   <td style='foo'><td/>
   ...
   <td>1<td/>
   <td>2<td/>
   <td>3<td/>
</tr>
所以

基本上我想要最后 3 个 td,所以首先我得到行,然后我发送了 Xpath。像这样:

var row = driver.FinElement(By.Id("something"));
ReadOnlyCollection<IWebElement> items = row.FindElements(By.Xpath(./td[not(contains(@style, 'foo'))];

但结果是我得到了tr的所有孩子。

知道为什么 Xpath 在 Chrome 开发人员工具上运行并且不能与 selenimun IE 驱动程序一起使用吗?

与Chrome相比,IE格式化样式属性。例如,如果 HTML 中的样式是:

<td style='DISPLAY:BLOCK;'>

IE 会将其更改为:

<td style='display: block;'>

因此,使用Chrome //td[@style='DISPLAY:BLOCK;']将返回匹配项,而IE将不返回匹配项。

现在,以您的示例为例,获取最后 3 个元素的解决方案是获取没有样式属性的所有<td>

./td[not(@style)]

您还可以规范化大小写并使用 translate 删除空格:

./td[not(contains(translate(@style,'FO ','fo'), 'foo'))]
  1. 你能试试以下吗:

    .//td[not(contains(@style, 'foo')  // double back slash for child element
    

从文档访问孩子

  1. 请确保您没有错误匹配大小写,因为contains区分大小写。回答如何在 xpath 中使用 not contains()?

最新更新