1

How can I find an option1 using xpath ?

Note: id is generated after each build.

i tried this and does not work :

/li[@class='itemL' and contains(text(),'option1'])

Input HTML snippet

<div id="list-1721" class="x-list x-list-floating x-layer x-boundlist-default" ">
<div id="list-1721-listEl" class="x-list-list-ct" style="overflow: auto; height: auto;">
<ul>
<li class="x-list-item itemL" role="option">option1</li>
<li class="x-list-item itemL" role="option">option2</li>
</ul>
</div>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356

2 Answers2

2

The xpath you attempted fails because @class='itemL' is doing an exact match against class attribute.

You can do similar to what you did with the text and use contains for the class attribute:

//li[contains(@class, 'itemL') and contains(text(), 'option1')]

Note that this would also match li elements where the class is "startitemL", "itemLend", etc. If you need to protect against that, then you will want to use one of the following to check for whole words.

Checking whole words in xpath 1.0:

//li[contains(concat(' ', @class, ' '), ' itemL ') and contains(text(), 'option1')]

Checking whole words in xpath 2.0:

//li[tokenize(@class,'\s+')='itemL' and contains(text(), 'option1')]
Justin Ko
  • 46,526
  • 5
  • 91
  • 101
0

If you are using c# you can check out this linq-esq library for generating xpath using lambda expressions.

http://www.syntaxsuccess.com/viewarticle/how-to-create-xpath-using-linq

This xpath can be expressed with the following expression:

      var xpath = CreateXpath.Where(e => e.TargetElementName == "li" 
                                   && e.TargetElementText.Contains("option1") 
                                   && e.Attribute("class").Contains("itemL"));

Generated xpath: //li[contains(@class,'itemL') and contains(text(),'option1')]

You can also make it more strict if you like by using equal operators:

          var xpath = CreateXpath.Where(e => e.TargetElementName == "li" 
                                       && e.TargetElementText == "option1" 
                                       && e.Attribute("class").Text == "itemL");

Generated xpath: //li[@class='option1' and text()='itemL']
TGH
  • 38,769
  • 12
  • 102
  • 135