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");
}
问题:
回答1:
You can open link in new window using below code :
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);
Generally we press SHIFT key and click using mouse to open link in new window , I did same thing here via code in selenium.
回答2:
Yet another way is injecting JS to set the target attribute on a link:
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();
The result line can probably be ignored but I found this being more reliable.
By the way:
1) Never compare to true or false. Instead of
if (condition != true)
write
if (! condition)
2) Do not look up the same element every time. Look for it once and save the reference.
3) You can't click a link that is not displayed.
回答3:
You can use the below code snippet; just replace the locator with what you want, and it should work:
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();
The above snippet navigates to Google site, then right clicks on the concerned link "हिन्दी" in this case, and uses the down key twice to reach the option of "Open link in a new window" and then sends "Enter" key to click on it, which then opens a new window.
NOTE:- This works fine in Firefox and Chrome. In case of Internet Explorer, you might have to add one extra sendKeys(keys.DOWN)
and it should be good because the option for "Open link in a new window" comes in the third place. Please check the snippet change for the same, below:
act.moveToElement(driver.findElement(By.xpath("//a[.='हिन्दी']"))).contextClick().sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).build().perform();