Search code examples
javaseleniumnosuchelementexception

Selenium/Java No Such Element Exception for elements of a page after following a link from homepage


New to automation and could use some help here.

I am using Selenium Webdriver and Java on this website - Webdriver University and so far this code has been throwing No Such Element exception at "element.click()" step (i.e., doesn't find the element on page):

      driver.manage().window().maximize();
        driver.get("http://webdriveruniversity.com");

        Thread.sleep(3000);
// Follow the link to another page
        WebElement link = driver.findElementByXPath("(//div[@class=\"section-title\"])[6]");
        link.click();
        Thread.sleep(3000);
// Click on the element
        WebElement element = driver.findElementByXPath("(//button[@class='accordion'])[1]");
        element.click();

However, when I go to the linked page directly, it finds the element just fine

 driver.manage().window().maximize();
        driver.get("http://webdriveruniversity.com/Accordion/index.html");

// Click on the element
    WebElement element = driver.findElementByXPath("(//button[@class='accordion'])[1]");
        element.click();

I've used wait for element visibility and Thread sleeps, same results. Any idea what could be the issue here?


Solution

  • Did you notice that when you click the link, page is opened in new tab? That is your issue. You need to switch to new tab.

    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    
    driver.switchTo().window(tabs.get(1)); //here you are switch to second tab