R0SENAM R0SENAM - 26 days ago 8
Python Question

Select all the li's in ul before a li with specific class

Okay i have an html code that is of ul => li. I am selecting all the li's in ul but recently i noticed that there are some more li's being dynamically generated that i don't need. So i want to select all the li's before 1 li comes with a different class and all the li's after that one specific li's should also not be selected.

<ul id="ListViewInner">
<li id="item2cb555b5f1" _sp="p2045573.m1686.l0" class="sresult lvresult clearfix li" r="1"></li>
<li id="item3ad18af5b3" _sp="p2045573.m1686.l0" class="sresult lvresult clearfix li" r="2"></li>
<li id="item3ad18ab9f4" _sp="p2045573.m1686.l1024" class="sresult lvresult clearfix li" r="3"></li>
<li class="lvresult clearfix li"></li>
<li id="item2119fca550" _sp="p2045573.m1686.l1024" class="sresult lvresult clearfix li" r="1"></li>
<li id="item3ad1301a0d" _sp="p2045573.m1686.l1032" class="sresult lvresult clearfix li" r="2"></li>
</ul>


Like the above code I want to get all the li's before this li with class="lvresult clearfix li" appears.

currently my xpath is very simple and is like this:

//ul[@id="ListViewInner"]/li


please let me know if it is achievable using xpath or should I use css.

Answer

You can use following-sibling axis for this purpose :

//ul[@id="ListViewInner"]/li[following-sibling::li/@class='lvresult clearfix li']

demo

output :

<li id="item2cb555b5f1"
    _sp="p2045573.m1686.l0"
    class="sresult lvresult clearfix li"
    r="1"/>
<li id="item3ad18af5b3"
    _sp="p2045573.m1686.l0"
    class="sresult lvresult clearfix li"
    r="2"/>
<li id="item3ad18ab9f4"
    _sp="p2045573.m1686.l1024"
    class="sresult lvresult clearfix li"
    r="3"/>
Comments