Home > front end >  How to distinguish 2 button base on their parent/ancestor element in Selenium (PYTHON)?
How to distinguish 2 button base on their parent/ancestor element in Selenium (PYTHON)?

Time:11-18

<a href="/google.com">
<div> ABC </div>
<span>
<button class="btn"> Show more </button>
<span/>
</a>

<div>
<div>ABC</div>
<span>
<button class="btn"> Show more </button>
<span/>
</div>

As you guys see here, we have 2 BUTTONS and I need to click to BUTTON whose ancestor is not <a/> tag, because if I click to button whose ancestor is tag, it will redirect me to other pages. So I don't want this behaviour.

The obvious solution is I can use absolute Xpath for this, but it's not a good way because HTML DOM or css structure could be changed so it' s not stable.

So how can I distinguish 2 button, using ancestor or something related? I mean other better ways. Thank you guys for helping me so much!

CodePudding user response:

To select a button that has no a tag ancestor can be done with the following XPath:

//button[not(ancestor::a) and(contains(.,'Show more'))]
  • Related