Robot Framework验证是否已打开新的浏览器选项卡

时间:2013-06-21 00:19:39

标签: selenium selenium-webdriver robotframework

对于我们页面上的一些网站链接,有外部链接指示用户说Facebook和Twitter。链接使用HMTL标记target="_blank",以便为我们的Twitter页面打开一个新的浏览器选项卡。

我想验证1.新的浏览器选项卡是否已打开,2。将焦点设置为它以及3.在新浏览器选项卡中验证页面元素。一旦我专注于它,#3部分就足够了。任务#1和#2虽然,我无法弄清楚,也找不到任何人谈论这个。

使用Selenium2Library(WebDriver)

5 个答案:

答案 0 :(得分:2)

Selenium不支持标签(截至2013年6月,Selenium 2.33.0)并始终打开新窗口。如果你的测试打开一个新标签,祝你好运。

也就是说,如果它正确地打开了一个新窗口,请使用Select Window

Select Window | url=https://twitter.com/expectedPage

我在Java中使用的是WebDriver(2.33.0)代码,希望它会有所帮助。你所描述的问题是我的机器人知识开始脱落的地方。

@Test
public void targetBlankLinkTest() {
    // load the website and make sure only one window is opened
    driver.get(file("TargetBlankLinkTest.html"));
    assertEquals(1, driver.getWindowHandles().size());

    // click the link and assert that a new window has been opened      
    driver.findElement(By.linkText("Follow us on Twitter!")).click();
    Set<String> windowHandles = driver.getWindowHandles();
    assertEquals(2, windowHandles.size());

    // switch to the new window and do whatever you like
    // (Java doesn't have Switch Window functionality that can select by URL.
    // I could write it, but have been using this trick instead)
    for (String handle : windowHandles) {
        if (handle != driver.getWindowHandle()) {
            driver.switchTo().window(handle);
        }
    }
    assertThat(driver.getCurrentUrl(), containsString("twitter.com"));
}

答案 1 :(得分:1)

如果要验证是否已打开新选项卡,则可以在单击打开新选项卡的链接/元素之前和之后比较窗口句柄。只需遵循此代码可能会对您有所帮助。

此处$ {LINKDIN}是在新标签页中打开的元素。所以在点击之前将窗口句柄保存在变量中,再次单击该元素后,将窗口句柄保存在变量中。现在如果打开一个新的选项卡,那么两个变量值都会不同,如果没有打开新的选项卡,那么两个变量值都是相同的。这样你就可以验证新的开启。

 Go Back
 ${Current_window}        List Windows
 Click Element            ${LINKDIN}
 ${New_Windows_list}      List Windows
 Should Not Be Equal      ${Current_window}    ${New_Windows_list}

答案 2 :(得分:1)

使用Robot Selenium2Library关键字:

@{windows} =  List Windows
${numWindows} =  Get Length  ${windows}
${indexLast} =  Evaluate  ${numWindows}-1
Should Be True  ${numWindows} > 1
Select Window  @{windows}[${indexLast}]
Location Should Contain  /my/url/whatever
Title Should Be   myTitle
Page Should Contain   ...

你明白了。

答案 3 :(得分:0)

我建议:

1. First, acquire new window handle by using the switchTo() method.
2. Then bring that window into focus using a JavaScriptExecutor:
   ((JavascriptExecutor) myTestDriver).executeScript("window.focus();");
   Using switchTo() without a javascript executor to get focus , is not 
   very reliable in my opinion.
3.  Next, do what you need to do in that window.
4. Use driver.close() to close that window.
5.  Verify you are back at the parent window with focus.

答案 4 :(得分:0)

U可以使用以下代码将焦点设置在新窗口上:

点击元素$ {a_link_which_opensin_newtab} 选择窗口新建

现在您可以在新标签上执行操作了。如果您想切换回主标签,请使用

选择窗口主窗口

相关问题