从硒驱动程序打开新的选项卡铬不起作用 [英] Open new tab in chrome from selenium web-driver doesn't work
问题描述
代码语言c#
Selenium Webdriver
我尝试使用以下代码在Chrome中打开一个新选项卡:
操作action = new Actions(BrowserFactory.Driver);
action.SendKeys(Keys.Control +T).Build()。Perform();
字符串secondTabHandle = BrowserFactory.Driver.CurrentWindowHandle;
我在stackoverflow上找到了这段代码。
我也试过:
IWebElement body =
BrowserFactory.Driver.FindElement(By.TagName(body)) );
body.SendKeys(Keys.Control +'t');
body.SendKeys(Keys.Control +t);
那也行不通
没有任何结果使用此代码后。
有人可以帮助我,我做错了什么。
在此先感谢。 / p>
更好的解决方案不依赖于按下CTRL + T或其他任何东西,因为在同一浏览器上的不同版本,CTRL + T可能会导致不同的行为。
我更喜欢在浏览器上执行javascript以打开新选项卡的解决方案,因为selenium本身支持在浏览器中注入并执行javascript。
我们应该让JavaScript在浏览器上执行以下操作:
$ b
-
创建一个链接节点,并设置链接href是'about:blank'或者你想要打开的url,设置链接目标是'_blank'
-
将链接节点追加到当前打开页面的正文中
-
点击链接并从正文中删除链接
代码示例:
string newTabScript =var d = document中,a = d.createElement( 'A');
+a.target ='_ blank'; a.href ='{0}';
+a.innerHTML ='新标签';
+d.body.appendChild(a);
+a.click();
+a.parentNode.removeChild(a);
$ b $ public void newTab(string tabUrl)
{
if(String.IsNullOrEmpty(tabUrl){
tabUrl =about:blank;
}
IWebDriver driver; //假定在别处分配
IJavaScriptExecutor js =(IJavaScriptExecutor)驱动程序;
js.ExecuteScript(String.format(newTabScript,tabUrl));
}
Code language c# Selenium Webdriver
I'm trying to open in chrome a new tab with the following code:
Actions action = new Actions(BrowserFactory.Driver);
action.SendKeys(Keys.Control + "T").Build().Perform();
string secondTabHandle = BrowserFactory.Driver.CurrentWindowHandle;
I found this code on stackoverflow.
I also tried:
IWebElement body =
BrowserFactory.Driver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Control+'t');
body.SendKeys(Keys.Control+"t");
Thats also not working
Nothing happens after using this code.
Can someone help me what I am doing wrong.
Thanks in advance.
The better solution is not dependent press CTRL+T or whatever, because on different browser or different version on same brower, the CTRL+T may lead to different behaviour.
I prefer the solution to execute javascript on browser to open a new tab, becasuse inject and execute javascript on browser supported natively by selenium.
We should make the javascript do following things on browser:
create a link node, and set the link href is 'about:blank' or the url you want to open, set the link target is '_blank'
append the link node to body of current opening page
click the link and remove the link from body
code example:
string newTabScript = "var d=document,a=d.createElement('a');"
+ "a.target='_blank';a.href='{0}';"
+ "a.innerHTML='new tab';"
+ "d.body.appendChild(a);"
+ "a.click();"
+ "a.parentNode.removeChild(a);"
public void newTab(string tabUrl)
{
if(String.IsNullOrEmpty(tabUrl) {
tabUrl = "about:blank";
}
IWebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript(String.format(newTabScript, tabUrl));
}
这篇关于从硒驱动程序打开新的选项卡铬不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!