Selenium C# Open New Tab CTRL+T Not working with C

2019-02-16 23:56发布

static void Main()
{
    IWebDriver driver = new ChromeDriver();
    driver.Navigate().GoToUrl("http://google.com");
    IWebElement body = driver.FindElement(By.TagName("body"));

    body.SendKeys(Keys.Control + "t");

}

This is the code that I am trying to use to open a new tab and its not working, I am not getting any errors nothing, the driver opens Google and thats all.... I have searched a lot and found many tutorials even videos where people are using the exact same code and it works for them, but for me it doesnt and I can't figure it out...

I tried sending Keys.Shift + "t" to the search field and it works, it writes a capital T in the field

I have also tried

Actions act = new Actions(driver);
act.KeyDown(Keys.Control).SendKeys("t").Perform();

And it still does not work, but again if I change Keys.Control to Keys.Shift it writes, seems like nothing that involves Keys.Control is working!!

Edit: I have tried running the code with a IE Driver and it worked there, it opens new tab, but it does not open new tabs on Chrome?

4条回答
Root(大扎)
2楼-- · 2019-02-17 00:01

If your on a mac, use Keys.Command instead of Keys.Control:

body.SendKeys(Keys.Command + "t");
查看更多
叛逆
3楼-- · 2019-02-17 00:05

Try this

driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
driver.SwitchTo().Window(driver.WindowHandles.Last());
driver.Navigate().GoToUrl("http://www.google.com")
查看更多
冷血范
4楼-- · 2019-02-17 00:11

Looks like it's a "feature" of the chrome driver.

https://bugs.chromium.org/p/chromedriver/issues/detail?id=581

This is a limitation in the way we simulate keyboard input in ChromeDriver. Keys get sent directly to the render process, bypassing the browser process. So any keyboard shortcut handlers in the browser process will not be invoked by sendKeys().

查看更多
Lonely孤独者°
5楼-- · 2019-02-17 00:17

Thanks for the answers! I did it with JavaScript.

((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
查看更多
登录 后发表回答