首页 文章

属性值以特定字符串结尾的元素的XPath?

提问于
浏览
4

鉴于HTML包含:

<div tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination" class="panel panel-default"></div>

我们如何在XPath中编写以下表达式:

Find a <div> element whose tagname attribute ends with the string 'Destination'

我一直在寻找几天,我无法想出一些有用的东西 . 在众多中,我试过例如:

div[contains(@tagname, 'Destination')]

4 回答

  • 4

    XPath 2.0

    //div[ends-with(@tagname, 'Destination')]
    

    XPath 1.0

    //div[substring(@tagname,string-length(@tagname) -string-length('Destination') +1) 
          = 'Destination']
    
  • 1

    XPath 2或3:总是有正则表达式 .

    .//div[matches(@tagname,".*_Destination$")]
    
  • 3

    你可以使用 ends-with (Xpath 2.0)

    //div[ends-with(@tagname, 'Destination')]
    
  • 6

    你可以使用下面的xpath,它将适用于Xpath 1.0

    //div[string-length(substring-before(@tagname, 'Destination')) >= 0 and string-length(substring-after(@tagname, 'Destination')) = 0 and contains(@tagname, 'Destination')]

    基本上它会在第一次出现_1868418之前检查是否有任何字符串(或没有字符串),但是 Destination 之后不应该有任何文本 .

    测试输入:

    <root>
    <!--Ends with Destination-->
    <div tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination" class="panel panel-default"></div>
    <!--just Destination-->
    <div tagname="Destination" class="panel panel-default"></div>
    <!--Contains Destination-->
    <div tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination_some_text" class="panel panel-default"></div>
    <!--Doesn't contain destination-->
    <div tagname="779853cd-355b-4242-8399-dc15f95b3276" class="panel panel-default"></div>
    </root>
    

    测试输出:

    <div class="panel panel-default"
         tagname="779853cd-355b-4242-8399-dc15f95b3276_Destination"/>
    <div class="panel panel-default" tagname="Destination"/>
    

相关问题