【问题标题】:Problems matching div via xpath locators in Selenium通过 Selenium 中的 xpath 定位器匹配 div 的问题
【发布时间】:2014-08-28 20:33:27
【问题描述】:

我正在尝试使用正则表达式来匹配在其他可预测字符串中间包含不可预测数字的 id,例如:

<div id="type-84289-model" class="vehicle">

我尝试了各种方法,但似乎最明显的应该是:

By.xpath("//div[matches(@id, 'type-.+-model')]"));

但是没有找到该元素。谁能指出我正确的方向。

【问题讨论】:

  • 是 XPath 2 吗?我认为 XPath 1 不支持正则表达式。
  • 如果@curiosu 是对的,你可以试试[starts-with(@id, 'type-') and ends-with(@id, '-model')]
  • 我相信它支持 Xpath 2。根据我对 Selenium 的了解,它归结为您正在测试的浏览器支持什么,我一直在使用 Firefox 31.0。但是,我确实按照@Ciapan 的建议尝试使用 'starts-with' 和 'ends-with',但没有运气......我收到了 InvalidSelectorException 异常。
  • 我对 Firefox 支持 XPath 2.0 的暗示感到惊讶。你有这方面的参考吗?
  • 我对 Firefox 支持 XPath 2 的假设似乎是错误的。一些谷歌搜索表明 Firefox 确实不支持 2.0。

标签: java selenium xpath


【解决方案1】:

您可以使用以下 xpath 找到该元素:

driver.findElement(By.Xpath("//div[contains(@id, 'type-')][contains(@id, '-model')][@class='vehicle']"))

【讨论】:

  • 我至少会将第一个 contains() 更改为 starts-with()。它同样具有可读性,不太可能产生误报,并且可能更快。
【解决方案2】:

curiosu 说得对,XPath 1 不支持正则表达式,而且 Selenium 也不支持 XPath 2。:-(

正如您所指出的,ends-with() 在 XPath 1.0 中不存在。所以我们可以将 CiaPan 的回答改写如下:

By.xpath("//div[starts-with(@id, 'type-') and
   substring(@id, string-length(@id)-6) = '-model']"));

【讨论】:

  • 这确实可以匹配我的 div id,但我将@German Petrov 标记为答案,因为它会更容易在代码中阅读,并且有很多 div 可以匹配。感谢您的帮助,这绝对是一次很好的 selenium 和 xpath 学习体验!
【解决方案3】:

如果 id 总是以一个以连字符结尾的字符串开头,后跟一个数字,并以一个以连字符开头的字符串结尾,这可以工作:

//div[ contains (translate(@id, '1234567890',''),'--')]

在你的情况下

By.xpath("//div[ contains (translate(@id, '1234567890',''),'--')]");

【讨论】:

    【解决方案4】:

    你真的想使用 xpath 和 xpath 来定位元素吗?如果没有,而你只是想定位 div,那么你可以使用 next 选择器:

    driver.findElement(By.Css(".vehicle"));
    //or
    driver.findElement(By.Css("div[class='vehicle']"));
    

    UDPATE 如果您需要找到匹配模式type-...-model 的 div,您仍然可以使用 css 选择器。但是 AFAIK css 选择器不支持正则表达式,所以你可以使用starts/ends with attributes: Smth like this:

    //find all divs which id starts with type
    driver.findElement(By.Css("div[class^='type']"))
    //find all divs which id ends with model
    driver.findElement(By.Css("div[class$='model']"))
    //find all divs which id starts with type and ends with model
    driver.findElement(By.Css("div[class^='type'][class$='model']"))
    

    现在应该可以工作了。

    【讨论】:

    • 他需要找到一个id匹配type-...-model的div。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多