使用JavascriptExecutor发送Keys并单击web元素 [英] Using JavascriptExecutor to sendKeys plus click on web element

查看:617
本文介绍了使用JavascriptExecutor发送Keys并单击web元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在新标签页中打开链接,然后在Firefox浏览器中使用Java中的selenium切换到该标签页。我的理解是,为了做到这一点,我需要使用发送键组合。

I'm trying to open a link in a new tab, then switch to that tab, in a Firefox browser, using selenium in Java. It's my understanding that in order to do this, I need to use a send keys combination.

为了在同一窗口中打开链接,我一直在使用类似这样的事情:

In order to open the link in the same window, I've been using something like this:

WebElement we = driver.findElement(By.xpath("//*[@id='btn']"));

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", we);

以上对我来说工作正常。

The above was working fine for me.

现在我正在尝试发送凯斯,如下所示,这不起作用:

Now I'm trying to also sendKeys, as in below, which is not working:

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("keyDown(Keys.CONTROL)
                        .keyDown(Keys.SHIFT)
                        .click(arguments[0])
                        .keyUp(Keys.CONTROL)
                        .keyUp(Keys.SHIFT);", we);

有什么建议吗?我无法弄清楚sendKeys到JavascriptExecutor的正确语法。我已经看过一些使用Actions的类似解决方案,但这对我来说也不起作用。

Any advice? I can't figure out the correct syntax to sendKeys to JavascriptExecutor. I've seen some similar solutions using Actions, but this hasn't worked for me either.

推荐答案

尝试下面的代码打开页面上的任何链接到新标签&切换到该选项卡。在那里进行操作&返回第一个标签进一步执行。

try below code to open any link on page to new tab & switch to that tab. Perform operations there & go back to first tab for further execution.

WebDriver driver = new FirefoxDriver();
        driver.get("http://stackoverflow.com/");
        WebElement e = driver.findElement(By.xpath(".//*[@id='nav-questions']"));       
        Actions action = new Actions(driver); 
        action.keyDown(Keys.CONTROL).build().perform(); //press control key
        e.click();
        Thread.sleep(10000); // wait till your page loads in new tab
        action.keyUp(Keys.CONTROL).build().perform(); //release control key
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //move to new tab
        driver.navigate().refresh(); // refresh page
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click(); //perform any action in new tab. I am just clicking logo
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); //switch to first tab
        driver.navigate().refresh(); 
        driver.findElement(By.xpath(".//*[@id='hlogo']/a")).click();// refresh first tab & continue with your further work.I am just clicking logo

这篇关于使用JavascriptExecutor发送Keys并单击web元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆