Home > Software design >  Can't find out the xpath from following dom code image
Can't find out the xpath from following dom code image

Time:12-01

enter image description here

I want to perform click on add to kart button action, but this same DOM code is used in 30 more items only product name is different which is in text.

I want to perform click on add to kart button action, but this same DOM code is used in 30 more items only product name is different which is in text.

CodePudding user response:

basically if the product name is the only thing unique, you need to find the product first and then use its parent element to reach the click button.

product = driver.find_element(value=f"//*[contains(text(), '{product_name}')]", by=By.XPATH)
parent_element = product.find_element(value="..", by=By.XPATH)
button = parent_element.find_element(value="button", by=By.TAG_NAME)
button.click()

edit: looks like i wrote the solution for python, but you can do the same thing in java as well.

CodePudding user response:

As @Saba mentioned, if the only unique thing in DOM is the product name, then you have to rely on it for your locators.

If you can use partial product names, this code would work to create a selector to find and click the element by:

String productNamePartial = "Brocolli";
String xpath = String.format("//*[contains(text(),'%s')]/../div/button", productNamePartial);

If you need to use the exact titles, this should work:

String productNameExact = "Brocolli - 1 Kg";
String xpath = String.format("//*[text() = '%s']/../div/button", productNameExact);
  • Related