2014-02-27 33 views
0

我是XPath新手,需要一些帮助。使用xpath匹配包含任何整数的字符串(0到9之间)

系统自动生成看起来像这样的ID:

<input type="file" class="form-file" size="22" 
     name="files[entry-23245_field_entry_attachment_und_0]" 
     id="edit-entry-23245-field-entry-attachment-und-0-upload" 
     style="background-color: transparent;"> 

我能够找到使用XPath或CSS但是ID字符串的变化,因为这范围内的数字的ID是随机生成所以未来我的测试运行时,它失败,因为它无法找到字符串。

我想知道,如果它是在所有可能写的XPath表达式将寻找一切从字符串edit-entry-的开始,然后一些如何寻找一个字符串-23245-内0-9之间的任意整数,然后也匹配结束部分field-entry-attachment-und-0-upload。通过这种方式,当我的测试运行时,即使字符串中的数字发生变化,也可以随时查找元素。 iv尝试将\d+添加到我的xpath中,但似乎没有提取它。

这是XPath:

//*[@id="edit-entry-23245-field-entry-attachment-und-0-upload"] 

回答

0

那是因为你的XPath是没有提取正确的属性。使用这样的XPath来获取元素的ID:

//input[@type="file" and @class="form-file"]/@id 

这个表达式应该提取你正在寻找的价值:

/edit-entry-\d+-field-entry-attachment-und-0-upload/ 

如果\ d +不适合你的工作,这是另一个可能性:

/edit-entry-[0-9]+-field-entry-attachment-und-0-upload/ 
+0

谢谢Severin。可以使用xpath构造的正则表达式?请告诉我这将如何写入xpath? – user2240134

+0

它不可能做到这一点。你需要提取id并使用提供的正则表达式匹配它。 – Severin

+0

再次感谢。我正在阅读这篇文章(http://stackoverflow.com/questions/405060/can-i-use-a-regex-in-an-xpath-expression),并认为它可能在xpath中的用户“包含”,所以认为它可能会说@id包含“[0-9]”。或者我感到困惑? – user2240134

0

只是一个解决办法的想法,因为we can't use regex in pure XPath

如果你只需要使用ID等于"edit-entry-[arbitrary-characters-here]-field-entry-attachment-und-0-upload"匹配<input>元素,我们可以使用starts-with()ends-with()功能是这样的:

//* 
    [starts-with(@id, "edit-entry-") 
     and 
    ends-with(@id, "-field-entry-attachment-und-0-upload")] 

并且如果你使用XPath 1.0,其中ends-with()功能不可用:

//* 
    [starts-with(@id, "edit-entry-") 
     and 
    (
     "-field-entry-attachment-und-0-upload" 
      = 
      substring(@id, string-length(@id) - string-length("-field-entry-attachment-und-0-upload") +1) 
    ) 
    ] 
相关问题