这是我的代码 wait方法不起作用 切换窗口无法正常工作 请帮我解决这个问题
import java.util.concurrent.ForkJoinPool.ManagedBlocker;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandling extends BaseClass
{
public static void main(String args[])
{
System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"\\driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\driver\\chromedriver.exe");
//WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("file://D:/8850OS_Code/Chapter 3/HTML/Window.html");
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
String window1 = driver.getWindowHandle();
System.out.println("First Window Handle is: " + window1);
WebElement link = driver.findElement(By.linkText("Google Search"));
link.click();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
String window2 = driver.getWindowHandle();
System.out.println("Second Window Handle is: " + window2);
System.out.println("Number of Window Handles so for: "+ driver.getWindowHandles().size());
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.switchTo().window(window1);
System.out.println("task done ");
}
}
谢谢
答案 0 :(得分:0)
切换窗口对您没有用,因为您切换到当前关注的(第一个)窗口。如果您检查window1
和window2
值,您会看到它们是相同的:第一个窗口的窗口句柄。要切换到新窗口,您需要切换到与当前窗口句柄不同的句柄
String window1 = driver.getWindowHandle();
for (String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(window1)) {
driver.switchTo().window(windowHandle);
}
}
String window2 = driver.getWindowHandle(); // now it will be the window handle of the second window
关闭新窗口并切换回来
driver.close();
driver.switchTo().window(window1);
至于等待,implicitlyWait
在创建WebDriver
后定义一次,它将在驱动程序的整个生命周期内有效,这意味着驱动程序将等待向上< / strong>到指定的时间,直到使用driver.findElement()
时找到元素。您可以看到有关等待here的更多信息。