Home > database >  org.openqa.selenium.NoSuchElementException: no such element (Switch to Frames by Index)
org.openqa.selenium.NoSuchElementException: no such element (Switch to Frames by Index)

Time:10-10

I'm trying to learn selenium and I had trouble with this step. Trying to find frames with index and failed but when I try to find with string it success. So what is the problem about finding frames with index. Here is my code.

public class Test3 {

WebDriver driver;

@Test
public void test_3(){

    System.setProperty("webdriver.chrome.driver","drivers/chromedriver.exe");
    driver = new ChromeDriver();
    driver.get("https://demoqa.com/frames");
    driver.manage().window().maximize();


    //driver.switchTo().frame("frame1");
    driver.switchTo().frame(0);


    WebElement frame1 = driver.findElement(By.id("sampleHeading"));
    String text = frame1.getText();
    System.out.println(text);

}

}

Error Message: "org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#sampleHeading"}"

CodePudding user response:

It can not be found because there are other iframes before the one that you are targeting. The one that you wish for is the 3rd one - frame(2). You can set breakpoint and inspect the page in the dev tools (F12 > Element > Ctrl F) with the followint xpath - //iframe. You will see how many iframes there are in the page. So the best is handling iframes by names or ids because otherwise the test can fail easily.

  • Related