Skip to main content
 首页 » 编程设计

c#之切换选项卡在 Selenium Webdriver 中不起作用

2024年05月10日41小虾米

我用 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);