Selenium is unable to find element in a Modal wind

2019-07-11 02:38发布

I have a page in which I click on a link which opens a new Modal window which has an iframe. I switched to the iframe and performed some validation, then click on the link in that Modal window which in turn opens a second new Modal window with an iframe. I am facing issue clicking on any element in that second new Modal window.

Here is my code.

WebElement Hotelname = driver.findElement(By.cssSelector(".hotelTitleZone2>a"));
Hotelname.click(); \\This will open a new Pop up.

driver.switchTo().frame(1);
\\perform some validation
String parentHandle = driver.getWindowHandle();
driver.findElement(By.linkText("View on a Map")).click(); \\This will open second pop up Modal window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); 
}
driver.switchTo().defaultContent();
driver.switchTo().frame(1); \\switching to frame
driver.findElement(By.linkText("Close")).click();

When I am running this code, I am getting an error:

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"Close"}

I tried with or without switching to default content, without switching to frame in second Modal window but result is always the same.

Any help is appreciated ? Thanks.

1条回答
Fickle 薄情
2楼-- · 2019-07-11 03:11

My understanding is:

  1. start from the default window
  2. click to open the first Modal window that has an iframe
  3. Switch to this new iframe (index = 1)
  4. Get the ID for the current window handle, which is the default window handle
  5. click to open the second Modal window that has a second iframe
  6. switch to the second Modal window
  7. switch back to the default window
  8. switch to iframe (index = 1)
  9. Find the button you are after

There are a few confusions here:

  • in step 4 above, you used String parentHandle = driver.getWindowHandle(); to store the original default window handle but you have never used it, instead, you use driver.switchTo().defaultContent();
  • What happened to the first Modal window after you clicked it? Did it close? if it had not closed, its iframe would still be iframe (index=1), this would explain why you could not find your button from the iframe (index=1); as your button would reside on the iframe that belongs to the second Modal window, which is likely to be iframe (index=2). You may use driver.switchTo().frame(2); to address it instead. To be sure, you can inspect HTML elements to see how many iframes are present and to which Modal windows they belong to.

Hope you will find it useful.

查看更多
登录 后发表回答