繁体   English   中英

切换标签在Selenium Webdriver中不起作用

[英]Switching tabs not working in Selenium Webdriver

我用C#编写了这段代码,但这对我不起作用。

第二个网址仍然在第一个标签中打开,虽然我切换了标签并更新了句柄。

// open first page in first tab
string firstPageUrl = "http://google.com";
driver.Navigate().GoToUrl(firstPageUrl);
// getting handle to first tab
string firstTabHandle = driver.CurrentWindowHandle;

// open new tab
Actions action = new Actions(driver);
action.SendKeys(OpenQA.Selenium.Keys.Control + "t").Build().Perform();
string secondTabHandle = driver.CurrentWindowHandle;

// open second page in second tab
driver.SwitchTo().Window(secondTabHandle);
string secondPageUrl = "http://bbc.com";
driver.Navigate().GoToUrl(secondPageUrl); // FAILED, page is opened in first tab -.-
Thread.Sleep(2000); // slow down a bit to see tab change

// swtich to first tab
action.SendKeys(OpenQA.Selenium.Keys.Control + "1").Build().Perform();
driver.SwitchTo().Window(firstTabHandle);
Thread.Sleep(1000);
action.SendKeys(OpenQA.Selenium.Keys.Control + "2").Build().Perform();

我正在使用最新的Chrome驱动程序。

有任何想法吗?

编辑:

这不重复。 我不是在这里打开链接,我想导航到我提供的URL。 另外,我按照建议使用CurrentWindowHandle ,但它对我不起作用。

string secondTabHandle = driver.CurrentWindowHandle; 仍然返回第一个选项卡,即使第二个选项卡覆盖第一个选项卡。 尝试这个

string firstTabHandle = driver.getWindowHandle();

Actions action = new Actions(driver);
action.SendKeys(OpenQA.Selenium.Keys.Control + "t").Build().Perform();

// switch to the new tab
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(firstTabHandle))
    {
        driver.switchTo().window(handle);
    }
}

// close the second tab and switch back to the first tab
driver.close();
driver.switchTo().window(firstTabHandle);

不完全确定这是否与您的问题有关(但我认为可能是这样):

我发现,使用selenium,使用Thread.Sleep()的更好的替代方法是使用:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));

第一个参数是你正在使用的selenium驱动程序,第二个参数是你想要在放弃之前等待的时间(超时)

然后你可以打电话:

wait.Until(condition);

condition是你想要等待的地方。 有一个selenium类提供了各种有用的条件,称为ExpectedConditions ,例如:

ExpectedConditions.ElementToBeClickable(By by)

等待特定可点击元素准备点击。

事实上,我发现每当页面内容发生变化时,最好等待下一个你正在使用的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM