切换选项卡在硒网络驱动程序中不起作用
本文关键字:网络 驱动程序 不起作用 选项 | 更新日期: 2023-09-27 18:34:07
我用C#编写了这段代码,但它对我不起作用。
第二个 url 仍在第一个选项卡中打开,尽管我切换了选项卡并更新了句柄。
// 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);
不完全确定这是否与您的问题有关(但我认为可能是):
我发现,对于硒,使用Thread.Sleep()
更好的替代方案是使用:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
其中第一个参数是你正在使用的硒驱动程序,第二个参数是你想在放弃之前等待多长时间(超时)
然后,您可以致电:
wait.Until(condition);
condition
是你想等待的。有一个硒类提供了各种有用的条件,称为ExpectedConditions
,例如:
ExpectedConditions.ElementToBeClickable(By by)
这将等待特定的可点击元素准备好点击。
事实上,我发现每当页面内容发生变化时,最好像这样等待您接下来使用的元素。