It appears you're experiencing an issue where your Selenium automation code is clicking on the wrong element when attempting to select a vehicle by its title. Let's analyze your code and pinpoint potential problems, then provide solutions to ensure that the correct vehicle is clicked.
Understanding the Code:
-
Element Locator:
@FindBy(xpath = "//div[@class='vehicle-select-card']/span[@class='vehicle-title']")
private List<WebElement> vehicleTitles;
You're locating all <span> elements with the class vehicle-title that are direct children of <div> elements with the class vehicle-select-card.
-
Click Method:
public void clickVehicleByTitle(String title) {
getDriverManager().waitForMultipleElementsToBeClickable(vehicleTitles.toArray(new WebElement[0]));
vehicleTitles.stream()
.filter(element -> getDriverManager()
.scrollToElement(getDriverManager()
.waitForElementToBeClickable(element))
.getText().trim().equals(title))
.findFirst()
.ifPresent(WebElement::click);
}
This method waits for all vehicleTitles elements to be clickable, filters them based on the text matching the provided title, and clicks on the first matching element.
Possible Causes of the Issue:
-
Incorrect Element Clicked:
- The
click() action is performed on the <span> element (vehicle-title), which might not be the correct element to interact with. Often, clicking on a nested <span> doesn't trigger the expected action if the clickable area is actually the parent <div> or another element.
-
Dynamic Content or Stale Elements:
- If the page updates dynamically (e.g., AJAX calls), the list of
vehicleTitles might become stale after the page has loaded or changed, leading to StaleElementReferenceException or unexpected behavior.
-
Text Mismatch:
- The text retrieved using
getText() might not match due to leading/trailing whitespaces, hidden characters, or case sensitivity.
-
Multiple Elements with Similar Titles:
- If there are multiple vehicle titles with similar or identical text, the
findFirst() might pick the wrong one.
Solutions:
-
Adjust the Element to Click:
-
Instead of clicking on the <span> element, click on the parent <div> or the element that actually responds to click events.
-
Updated Locator:
@FindBy(xpath = "//div[@class='vehicle-select-card']")
private List<WebElement> vehicleCards;
-
Updated Method:
public void clickVehicleByTitle(String title) {
getDriverManager().waitForMultipleElementsToBeClickable(vehicleCards.toArray(new WebElement[0]));
vehicleCards.stream()
.filter(card -> {
WebElement titleElement = card.findElement(By.className("vehicle-title"));
String actualTitle = titleElement.getText().trim();
return actualTitle.equals(title);
})
.findFirst()
.ifPresent(card -> {
getDriverManager().scrollToElement(getDriverManager()
.waitForElementToBeClickable(card))
.click();
});
}
By doing this, you ensure that you're clicking on the entire card, which is more likely to trigger the correct action.
-
Ensure Text Matches Exactly:
-
Trim and Normalize the Text:
String actualTitle = titleElement.getText().trim();
-
Check for Case Sensitivity:
-
If titles might have varying cases, use equalsIgnoreCase():
return actualTitle.equalsIgnoreCase(title);
-
Handle Extra Whitespace:
-
Add Debugging Statements:
-
Log Each Title:
vehicleCards.forEach(card -> {
WebElement titleElement = card.findElement(By.className("vehicle-title"));
String actualTitle = titleElement.getText().trim();
System.out.println("Found title: " + actualTitle);
});
This helps verify that you're retrieving the correct titles.
-
Wait for Elements Properly:
Revised Complete Code:
@FindBy(xpath = "//div[@class='vehicle-select-card']")
private List<WebElement> vehicleCards;
public void clickVehicleByTitle(String title) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for vehicle cards to be visible
wait.until(ExpectedConditions.visibilityOfAllElements(vehicleCards));
// Loop through each vehicle card
vehicleCards.stream()
.filter(card -> {
// Find the title element within the card
WebElement titleElement = card.findElement(By.className("vehicle-title"));
// Scroll to the title element
getDriverManager().scrollToElement(titleElement);
// Get and normalize the text
String actualTitle = titleElement.getText().trim().replaceAll("\\s+", " ");
// Debugging: Print out the title
System.out.println("Found title: '" + actualTitle + "'");
// Compare with the provided title
return actualTitle.equalsIgnoreCase(title.trim().replaceAll("\\s+", " "));
})
.findFirst()
.ifPresent(card -> {
// Scroll to the card
getDriverManager().scrollToElement(card);
// Wait for the card to be clickable
wait.until(ExpectedConditions.elementToBeClickable(card));
// Click on the card
card.click();
// Alternatively, use JavaScriptExecutor if click() doesn't work
// JavascriptExecutor js = (JavascriptExecutor) driver;
// js.executeScript("arguments[0].click();", card);
});
}
Additional Tips:
-
Ensure Single Responsibility:
- The method
clickVehicleByTitle should only handle clicking on the vehicle and not be responsible for waiting or scrolling. Consider refactoring your code to separate concerns.
-
Use Explicit Waits Wisely:
- Overusing waits can lead to performance issues. Use them only where necessary.
-
Consult the AUT (Application Under Test):
- Inspect the HTML structure of the vehicle cards to ensure that the locators correctly identify the elements you intend to interact with.
-
Handle Exceptions:
- Add exception handling to catch any
NoSuchElementException or StaleElementReferenceException that might occur due to dynamic content.
Conclusion:
By adjusting the element you're clicking on and ensuring that the text comparison is accurate, you should be able to click on the correct vehicle card. Adding debugging statements and carefully examining the actual titles retrieved during the test run can also help diagnose any discrepancies between the expected and actual behaviors.