eclipse 我可以在java中使用selenium webdriver通过页面标题在窗口之间切换吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36419200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can i switch between windows by its page title using selenium webdriver in java?
提问by Chandni
Found answers related to switching between windows using getDriver().getWindowHandles() and iterating through it.
找到了与使用 getDriver().getWindowHandles() 和迭代在窗口之间切换相关的答案。
But I would like to know if there is any way to switch between windows using page title in selenium webdriver using java.
但我想知道是否有任何方法可以在使用 java 的 selenium webdriver 中使用页面标题在窗口之间切换。
Note : I am a newbie to Selenium Framework
注意:我是 Selenium 框架的新手
回答by Tharaka Deshan
Yes you can.
是的你可以。
String your_title = "This is the Title";
String currentWindow = driver.getWindowHandle(); //will keep current window to switch back
for(String winHandle : driver.getWindowHandles()){
if (driver.switchTo().window(winHandle).getTitle().equals(your_title)) {
//This is the one you're looking for
break;
}
else {
driver.switchTo().window(currentWindow);
}
}
回答by Tom Trumper
If you have the exact title of the window you want to switch focus to (i.e. the exact content of the top-level <title>
tag of the window), then you can simply do the following:
如果您有要将焦点切换到的窗口的确切标题(即<title>
窗口顶级标签的确切内容),那么您只需执行以下操作:
driver.switchTo().window("Whatever the title is, as a String");
If you only have the partial title of the window you want to switch focus to, then you should iterate over the available windows by their handles as the other answers suggest.
如果您只有想要将焦点切换到的窗口的部分标题,那么您应该按照其他答案的建议通过句柄遍历可用窗口。
回答by eduliant
Hi you can try like below
嗨,您可以尝试如下
driver.get("http://www.seleniumhq.com");
// for understanding point please open a new tab
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL + "t");
// note new tab title will be blank as we have not opened anything in it.
// Store the current window handle- the parent one
String winHandleBefore = driver.getWindowHandle();
// store all the windows
Set<String> handle= driver.getWindowHandles();
// iterate over window handles
for(String mywindows : handle){
// store window title
String myTitle = driver.switchTo().window(mywindows).getTitle();
// now apply the condition - moving to the window with blank title
if(myTitle.equals("")){
// perform some action - as here m openning a new url
driver.get("http://docs.seleniumhq.org/download/");
}else{
driver.switchTo().window(winHandleBefore);
}
}
Hope this helps what you are looking for.
希望这对您正在寻找的东西有所帮助。