Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - Handling a popup window using selenium

I have a circumstance in which clicking a link webpage opens a popup window. And after the popup window opens the focus is in the popup window and master window is disabled. And i am unable to get the control transferred to the popup window. Please have a look at the following code.

driver.findElement(By.linkText("Click me")).click();// when this line of code is reached then a popup window opens.

System.out.println("After Clicking me"); // After the popup window opens this line of code is never executed.

I am unable to transfer the control from parent window to popup window. I am aware of the following command.

driver.switchTo().window("popup window");

But its not helping much. please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

driver.findElement(By.linkText("Click me")).click();// when this line of code is reached then a popup window opens.

System.out.println("After Clicking me"); // After the popup window opens this line of code is never executed.

The line of code is never executed because the process is waiting for the popup to be handled.

getWindowHandles() works properly in this situation.

Example:

//handle of the master window before clicking the link
String master = driver.getWindowHandle();

driver.findElement(By.linkText("Click me")).click();

//logic for waiting for the popup, checking the size to become greater than 1 or breaking after sometime to avoid the infinite loop.
int timeCount = 1;

do
{
   driver.getWindowHandles();
   Thread.sleep(200);
   timeCount++;
   if ( timeCount > 50 ) 
   {
       break;
   }
}
while ( driver.getWindowHandles().size == 1 );

//Assigning the handles to a set
Set<String> handles = driver.getWindowHandles();
//Switching to the popup window.
for ( String handle : handles )
{
    if(!handle.equals(master))
    {
         driver.switchTo().window(handle);
    }
}

Now driver is switched to the popup window. If the popup window has a frame then you need to switch to the frame before identifying elements in it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...