【问题标题】:Selenium: is there a way to write an xpath to get elements that contains text that ends with numbersSelenium:有没有办法编写一个 xpath 来获取包含以数字结尾的文本的元素
【发布时间】:2019-10-22 20:37:06
【问题描述】:

我正在尝试编写一个 xpath,它选择包含以数字结尾并用大括号括起来的文本的所有元素。数字可以是任何数字,也可以是任意位数。这在 XPath1.0 中可行吗?我不能使用正则表达式,因为它在 XPath1.0 中是不允许的

<div class = '12345' >
   <div class = '98231'>I want this (101)</div>
   <div class = '98232'>I don't want this 101</div>
   <div class = '98233'>I want this (1)</div>
   <div class = '98234'>I don't want this (10A1)</div>
</div>

【问题讨论】:

  • 您能分享您为解决问题而编写的代码吗?
  • 您只能获取所有元素,然后使用您的代码绑定通过正则表达式进行过滤。

标签: selenium-webdriver xpath


【解决方案1】:

在 XPath-1.0 中,您不能使用 RegEx。
但是您可以使用fn:number() 函数来检查给定的字符串是否可以是使用fn:boolean 函数的有效数字:

/div/div[boolean(number(substring-before(substring-after(.,'('),')')))]

显然,这仅在字符串中没有其他括号时才有效。并且它不检查括号中的数字是否在字符串的末尾。要添加此进一步限制,请将表达式更改为

/div/div[not(boolean(string(normalize-space(substring-after(.,')'))))) and boolean(number(substring-before(substring-after(.,'('),')')))]

这增加了一个谓词来检查) 之后是否有除空格以外的字符。 fn:number() 函数会自动删除括号之间的前导和尾随空格。

【讨论】:

  • 正是我想要的。我根本不存在这些 xpath 函数。是否有网站/文档提供我可以参考的 xpath 的所有功能的详细信息。
  • 您可以随时参考XPath-1.0, XPath-2.0 and XPath-3.0/3.1中的函数库规范。谷歌搜索“XPath 函数”,你会发现像 this XPath-1.0 listthis XPath-2.0 list 这样的网站可能更容易阅读,但不太精确。
【解决方案2】:

尝试以下 xpath:

//div//div[text() and contains(text(),'(') and contains(text(),')')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    相关资源
    最近更新 更多