我遇到了许多在窗口之间切换的解决方案,其中之一是:
Set<String> allWindows = driver.getWindowHandles();
for(String currentWindow : allWindows){
driver.switchTo().window(currentWindow);
}
但是,我无法转到特定窗口。有人能告诉我如何从父窗口切换到第三个窗口(使用 java 客户端库)吗?
你快到了。如果你想切换到一个窗口,首先将窗口 id 存储在一个数组中并切换到某个特定的窗口。像下面这样的东西。如果您需要更多帮助,请告诉我。快乐编码。
Set handles = driver.getWindowHandles();
String[] individualHandle = new String[handles.size()];
Iterator it = handles.iterator();
int i =0;
while(it.hasNext())
{
individualHandle[i] = (String) it.next();
i++;
}
driver.switchTo().window(individualHandle[1]);
public static void switchWindow(String text) {
WebDriver popup = null;
Iterator<String> windowIterator = driver.getWindowHandles()
.iterator();
while (windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = driver.switchTo().window(windowHandle);
String title = popup.getTitle();
if (title.contains(text)) {
break;
}
}
}
这将为您提供包含某些文本的任何窗口,您不必具体。
以下方法将导航到特定窗口
public static void switchToParticularWindow(WebDriver driver, int index) throws InterruptedException {
ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(tabs.get(index));
Thread.sleep(2000);
logger.info("Switched to new tab");
}
公共类 WindowHandles {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://www.way2automation.com/lifetime-membership-club/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id=\"menu-item-25089\"]/a/span[2]")).click();
driver.findElement(By.xpath("//*[@id=\"ast-desktop-header\"]/div[1]/div/div/div/div[2]/div/div/div/a[1]")).click();
Set<String> window = driver.getWindowHandles();
Iterator<String> it =window.iterator();
while(it.hasNext())
{
String childWindow = it.next();
String windowTitle = driver.switchTo().window(childWindow).getTitle();
if(windowTitle.contains("Way2Automation"))
{
break;
}
}
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//*[@id=\"blueBarDOMInspector\"]/div/div/div/div[1]/a")).click();
System.out.println(driver.getTitle());
}
}