如何在使用java单击链接时打开新窗口

if(driver.findElement(By.xpath("xxx")).isDisplayed() != True){ // if clicked in the above condition is True then it has to be opened in a new window driver.findElement(By.xpath("xxx")).click(); } else { System.out.println("element not present -- so it entered the else loop"); } 

您可以使用以下代码在新窗口中打开链接:

 WebElement link = driver.findElement(By.xpath("your link xpath")); Actions newwin = new Actions(driver); newwin.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform(); Thread.sleep(6000); 

一般我们按SHIFT键并点击鼠标在新窗口中打开链接,我在这里通过selenium中的代码做了同样的事情。

另一种方法是注入JS以在链接上设置目标属性:

 WebElement link = driver.findElement(By.linkText("my link")); JavascriptExecutor js = (JavascriptExecutor) driver; String script = "return arguments[0].target='_blank'"; Object result = js.executeScript(script, link); link.click(); 

结果行可能会被忽略,但我发现这更可靠。


顺便说说:

1)永远不要与真或假相提并论。 代替

  if (condition != true) 

  if (! condition) 

2)每次都不要查找相同的元素。 查找一次并保存参考。

3)您无法单击未显示的链接。

您可以使用以下代码段; 只需用你想要的东西替换定位器 ,它应该工作:

 driver.get("https://www.google.co.in"); Actions act = new Actions(driver); act.moveToElement(driver.findElement(By.xpath("//a[.='हिन्दी']"))).contextClick().sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).build().perform(); 

以上代码段导航到Google网站,然后在这种情况下右键单击相关链接“हिन्दी” ,并使用向下键两次以达到“在新窗口中打开链接”选项,然后发送“Enter”键进行单击在它上面,然后打开一个新窗口。

注意: – 这在Firefox和Chrome中运行良好。 对于Internet Explorer,您可能需要添加一个额外的sendKeys(keys.DOWN) ,它应该是好的,因为“在新窗口中打开链接”选项排在第三位 。 请检查以下相同的代码段更改:

 act.moveToElement(driver.findElement(By.xpath("//a[.='हिन्दी']"))).contextClick().sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).build().perform();