Home > Software engineering >  Clicking on element by finding it first by column and row
Clicking on element by finding it first by column and row

Time:02-03

I'm trying to click on element in table that is only seperated by columns and every colum only has one row. The table looks like this enter image description here

I tried locating element like this

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, f"//div[@class='srb-ParticipantLabelCentered gl-Market_General-cn1 ' and contains(., '140.0')]/following::span[text() ='2.40']"))).click()

but instead of clicking on row that contains "2.40" and is next to 140.0 it clicks on row 2.40 that is next to 131.0. It clicks on first element that matches value "2.40". How could I make it so it clicks on 2.40 that is next to 140.0

CodePudding user response:

It seems you have two similar div elements with same class name and text value.

If so use last() option in xpath to get the last one, which should identify the expected element.

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, f"(//div[@class='srb-ParticipantLabelCentered gl-Market_General-cn1 ' and contains(., '140.0')])[last()]/following::span[text() ='2.40']"))).click()

This will work on both cases. If only one element or more than one elements.

CodePudding user response:

Assuming there are only 2 occurrence of 2.40, you can try the below XPath:

(//*[contains(text(),'2.40')])[2]

Explanation: searches all the nodes(//*) which contains text 2.40 and fetches the second occurrence([2])

  • Related