robertredrain
robertredrain

Reputation: 59

Two different elements with same xpath?

I am trying to test this website by using JUnit and Selenium: https://www.oanda.com/currency/converter/

I tried to select Unit from “Currency I Have” as well as "Currency I Want". Then I found out that the xpaths are the same. Only the "Currency I Have" codes can be run successfully. "Currency I want" always fail.

The Xpath is driver.findElement(By.xpath("//span[text() = 'GBP']")).click();

Could someone help on this? Thanks.

Code1:

public class Currency_I_Have {
    WebDriver driver = new FirefoxDriver();

    @Before
    public void setUp() throws Exception {
        driver.manage().window().maximize();
        driver.get("https://www.oanda.com/currency/converter/");
    }

    @Test
    public void test() {
        driver.findElement(By.id("quote_currency_input")).click();

        driver.findElement(By.xpath("//span[text() = 'GBP']")).click();
        WebElement Amount = driver.findElement(By.id("quote_amount_input"));
        Amount.clear();
        Amount.sendKeys("100");
    }
}

Code2:

public class Currency_I_Want {
    WebDriver driver = new FirefoxDriver();

    @Before
    public void setUp() throws Exception {
        driver.manage().window().maximize();
        driver.get("https://www.oanda.com/currency/converter/");
    }

    @Test
    public void test() {
        driver.findElement(By.id("base_currency_input")).click();

        driver.findElement(By.xpath("//span[text() = 'GBP']")).click();
        WebElement Amount = driver.findElement(By.id("base_amount_input"));
        Amount.clear();
        Amount.sendKeys("200");
    }
}

Upvotes: 1

Views: 2404

Answers (1)

Keith Tyler
Keith Tyler

Reputation: 825

I count 4 elements on that page matching that XPath. (Although on further inspection it looks like you could go with either in each pair, since they are dupes.) What you need to do is find unique parent elements for the specific span you want. For example the two unique matching elements could also be referenced more uniquely via:

//div[@id='quote_currency_selector']//span[text()='GBP']

(I think this is the one you want) The other one could be referenced more uniquely via:

//div[@id='base_currency_selector']//span[text()='GBP']

I got the "quote currency selector" and "base currency selector" bits from "ancestor" DIVs that were "higher up" the XML tree from the "GBP" entries in the drop downs.

Upvotes: 2

Related Questions