Search code examples
javascripthtmldomxpathcss-selectors

How can I find a relative xpath for buy button


I want to find the xpath of the buy button. I created the paths using copying through chrome but they are not working on everypage of the website where I require them to work. I require a path such that if the website changes in future, my xpath still works.

<div id="buySellOrder" class="valign-wrapper vspace-between width100 buySellOrder_bso21Parent__8UIa8">
    <div class="valign-wrapper vspace-between buySellOrder_bso21Main__KhLIN width100">
        <div class="width100 buySellOrder_bso21Lower__WiRcn absolute-center">
            <div class="width100">
                <div class="">
                    <div class="btn96DefaultClass absolute-center cur-po bodyBaseHeavy contentPrimary cur-po btn96MediumButton btn86FullWidth btn96ButtonLabel contentOnColour backgroundAccent btn96ButtonHover"><span class="">BUY</span></div>
                </div>
            </div>
        </div>
    </div>
</div>

I tried the following path but they are not working:

//*[contains(@class,"btn96ButtonLabel") and contains(@class,"contentOnColour") and contains(@class,"backgroundAccent") and contains(@class,"btn96ButtonHover") and .//span[contains(text(), "BUY")]

//*[@id="buySellOrder"][contains(@class,"btn96ButtonLabel") and contains(@class,"contentOnColour") and contains(@class,"backgroundAccent") and contains(@class,"btn96ButtonHover") and .//span[contains(text(), "BUY")]


Solution

  • You can may be directly do this:

    (//*[.='BUY'])[1]

    • '.=' is equal to text()
    • ()[1]- gets the first element with BUY text in the page, if you need the second one in the same page just increase the index by 1.