google-chrome - 在新标签页中打开链接适用于 Firefox,但不适用于使用 Selenium 的 Chrome 浏览器

标签 google-chrome firefox selenium selenium-webdriver

我有一个测试,我需要在新标签页中打开一个链接。这必须在 Firefox 和 Chrome 中工作。我首先尝试使用 Google 页面上的 Gmail 链接。

在 Firefox 上运行完美,Gmail 在新选项卡中打开。 但在 Chrome 上,Gmail 页面在同一窗口中打开,右键单击后菜单保持打开状态。有人遇到过这个问题吗?

下面是我的示例代码。

Firefox 代码:

FirefoxProfile myprofile;
ProfilesIni profile = new ProfilesIni();            
myprofile = profile.getProfile("SeleniumAuto");             
WebDriver driver = new FirefoxDriver(myprofile);
driver.get("http://www.google.com");    
driver.manage().window().maximize();

Actions a = new Actions(driver);
WebElement e = driver.findElement(By.xpath("/html/body/div/div[3]/div[1]/div/div/div/div[1]/div[2]/a"));
a.moveToElement(e);
a.contextClick(e).sendKeys(Keys.ARROW_DOWN)
 .sendKeys(Keys.ENTER).build().perform();            

Chrome 代码:

ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.google.com");    
driver.manage().window().maximize();*/    

Actions a = new Actions(driver);
WebElement e = driver.findElement(By.xpath("/html/body/div/div[3]/div[1]/div/div/div/div[1]/div[2]/a"));
a.moveToElement(e);
a.contextClick(e).sendKeys(Keys.ARROW_DOWN)
 .sendKeys(Keys.ENTER).build().perform();

最佳答案

我遇到了同样的问题。显然,ARROW_DOWN 不起作用,所以我尝试使用组合键,它对我有用。代码如下:

1) 在新标签页中打开,焦点仍然在当前标签页上

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(your_path)));
actions.keyDown(Keys.CONTROL).perform();
driver.findElement(By.xpath(your_path)).click();
actions.keyUp(Keys.CONTROL);

2) 在新标签页中打开并移动到新标签页

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(your_path)));
actions.keyDown(Keys.CONTROL).perform();
actions.keyDown(Keys.SHIFT).perform();
driver.findElement(By.xpath(your_path)).click();
actions.keyUp(Keys.SHIFT);
actions.keyUp(Keys.CONTROL);

希望这对您有所帮助。

关于google-chrome - 在新标签页中打开链接适用于 Firefox,但不适用于使用 Selenium 的 Chrome 浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186944/

相关文章:

javascript - 如何在 Chrome 中的代码中设置 JavaScript 断点?

java - Selenium(OSX 和 Linux)抛出错误 org.openqa.selenium.SessionNotCreatedException : session not created: No matching capabilities found

java - 你如何让 selenium 识别页面已加载?

selenium - 基于云的测试自动化工具

google-chrome - 如何让 mapbox-gl-js webgl/opengl 在 ubuntu chrome 上工作?

javascript - 如何通过从外部源(数据库)提取值来动态调整 chrome 扩展的 manifest.json 的 "matches"键?

firefox - 媒体element.js音频设置在firefox中失败,在其他地方均可使用

firefox - Greasemonkey 脚本与 Firefox、Safari、Opera 和 chrome 的兼容性(onload 事件)

javascript - Cypress 模糊事件(当输入失去焦点时)不会用 headless "cypress run --browser firefox"触发,但可以与 "cypress open"一起使用

selenium - 继续刷新页面直到出现某个元素?