Home > Enterprise >  Selenium: locator for the button field
Selenium: locator for the button field

Time:08-03

I'm trying to write an automation script with Java and Selenium for this site, but I got stuck while trying to find a locator for the directions button.

Locator:

@FindBy(xpath = "//a[@href=\"/directions\"]")    
private WebElement directionsButton;

Methods:

public void clickOnDirectionsButton() {
        waitForElementAndClick(directionsButton);
    }
public void waitForElementAndClick(WebElement element) {
        getWebDriverWait().until(ExpectedConditions.elementToBeClickable(element)).click();
    }

private WebDriverWait getWebDriverWait() {
        return new WebDriverWait(getDriver(), Duration.ofSeconds(5));
    }

HTML:

<div >
        <a  title="Find the route" href="/directions"><img width="20" height="20" src="/assets/directions-6ae0ecdabcaa76d0d14dddddfa7d6381ecdd817b05f751ea422e53493945e942.png" /></a>
      </div>
    </div>
  </form>

When I launch the script, the browser is started, but then nothing is going on and the script ends with an exception as follows:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for frame to be available: [[ChromeDriver: chrome on MAC (4c996493878e66ee1e24eb2224a1175b)] -> xpath: //a[@href="/directions"]] (tried for 5 second(s) with 500 milliseconds interval)

I want the script to click on the directions button. How can I achieve such behavior?

CodePudding user response:

I see 2 anchor nodes with the same @href="/directions". The first one is hidden. Try to use this XPath:

//a[@title='Find directions between two points']

CodePudding user response:

The xpath based locator strategy which you have used:

@FindBy(xpath = "//a[@href=\"/directions\"]")    
private WebElement directionsButton;

doesn't identifies the desired element uniquely within the HTML but identifies two elements:

directions


Solution

To identify the element uniquely you can use either of the following locator strategies:

  • Using cssSelector:

    @FindBy(css = "div#content a[title='Find directions between two points'][href='/directions']")    
    private WebElement directionsButton;
    
  • Using xpath:

    @FindBy(xpath = "//div[@id='content']//a[@title='Find directions between two points' and @href='/directions']")    
    private WebElement directionsButton;
    
  • Related