我正在处理的测试页面是firefox中的http://www.quackit.com/html/templates/frames/frames_example_1.html。
在其中,我必须点击Code Generator
WebElement
并使用Selenium Webdriver
,JAVA截取已打开页面的屏幕截图。
无论我尝试了什么方法,Selenium都将异常视为
无法找到元素。
它的目标是_blank。
请找到以下代码
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Quackit {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.quackit.com/html/templates/frames/frames_example_1.html");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
String parentWindow = driver.getWindowHandle();
WebElement e = driver.findElement(By.linkText("Code Generator "));
// ensure that link always opens in the current window
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('target', arguments[1]);", e, "_self");
e.click();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source,new File ("./Screenshots/codegenerator.png"));
}
}
答案 0 :(得分:0)
这有效:
driver.switchTo().frame("content");
WebElement e = driver.findElement(By.xpath("//a[contains(.,'Code Generator')]"));
e.click();
您必须先切换到框架,然后使用contains()
找到元素。
答案 1 :(得分:0)
问题是Code Generator链接在frame / iframe内。所以如果元素在框架内,首先我们需要切换到框架,然后我们才能找到框架的元素。
完成框架内的工作或操作后,需要打开默认内容。
WebDriver driver = new FirefoxDriver();
driver.get("http://www.quackit.com/html/templates/frames/frames_example_1.html");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.switchTo().frame("content");
WebElement e = driver.findElement(By.linkText("Code Generator"));
e.click();
driver.switchTo().defaultContent();
//try for window handles here
谢谢你, 穆拉利