How do I select preceding sibling Xpath

You can do this with a single locator but it’s going to be a large one. I’ll walk you through how it’s constructed so hopefully it makes some sense.

This is the full XPath

//div[contains(@class,'slick-row')][./div[contains(@class,'r1')][text()=' ANTRA ']][./div[contains(@class,'r2')][text()=' DAS ']][./div[contains(@class,'r3')][text()=' 10/08/1988 ']]/div/input

At a high level, we’re finding a parent DIV that contains multiple elements with specific requirements… the right two names and DOB. Once we find that DIV, find the child DIV and child INPUT. Here are the details of each step:

I’ll reformat it into multiple lines so that I can break it down and explain it easier.

1 //div[contains(@class,'slick-row')]
2 [./div[contains(@class,'r1')][text()=' ANTRA ']]
3 [./div[contains(@class,'r2')][text()=' DAS ']]
4 [./div[contains(@class,'r3')][text()=' 10/08/1988 ']]
5 /div/input

Part 1 is pretty standard and you probably understand it… it finds a DIV that contains the class ‘slick-row’. This is a parent DIV to each block of HTML that represents a patient and their info. There is one of these for each patient. We need to add more filters to find the right one.

Part 2 is take the potential parent DIVs from Part 1 and find one that has a descendant DIV that has a class ‘r1’ and also contains the text ‘ ANTRA ‘ (note the spaces around the text).

Part 3 and 4 are parallels to Part 2… just add filters to the DIV from Part 1 where they contain the name and DOB.

Once we’ve found the right parent DIV that has met all the filters in Steps 2-4, we need to find the child DIV that has a child INPUT. That’s the final INPUT that needs to be clicked.

Now to the code. You no longer need (at least for this task) patientList and patientsDOB so they can be removed.

driver.findElement(By.xpath("//input[@id='txtSearchTextBox']")).sendKeys(Ex_FullName); // Reading fullname from Excel
driver.findElement(By.xpath("//input[@id='imgbtnSeach']")).click();
String firstName = " ANTRA "; // read from Excel?
String lastName = " DAS "; // read from Excel?
String DOB = patientsDOB.get(d).getText();
DataFormatter formatter = new DataFormatter();
String Ex_DOB = formatter.formatCellValue(sheet.getRow(r).getCell(3)); // read from Excel
driver.findElement(By.xpath("//div[contains(@class,'slick-row')][./div[contains(@class,'r1')][text()=' " + firstName + " ']][./div[contains(@class,'r2')][text()=' " + lastName + " ']][./div[contains(@class,'r3')][text()=' " + Ex_DOB + " ']]/div/input")).click();

I may have the first name and last name backwards so you may need to switch the variable names.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top