FirefoxDriver:如何禁用javascript,css并立即生成sendKeys类型?

使用FirefoxDriver编写测试时

我发现由于javascript和css正在执行,页面加载速度非常慢。 无论如何要禁用它吗? 有可能甚至安装Noscript插件到配置文件?

另外,sendKeys()实际上输出了文本。 但是,对于长文本来说这很慢,无论如何要立即在输入框中键入所有字符串?

您可以在FirefoxProfile禁用javaScript:

 FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("javascript.enabled", false); WebDriver driver = new FirefoxDriver(profile); 

我不认为有一种方法可以禁用CSS,这不是你应该做的 – 这可能会破坏你的web应用程序,禁用JavaScript也可能会这样做。

没有办法直接设置文本字段的值 – WebDriver旨在模拟真实用户“驱动”浏览器 – 这就是为什么只有sendKeys。

但是,您可以通过JavaScript调用设置元素的值(当然,如果您不禁用它)。 这对于长时间测试来说速度更快,但这不是用户交互的模拟,因此可能不会触发某些validation,因此请谨慎使用:

 private void setValue(WebElement element, String value) { ((JavascriptExecutor)driver).executeScript("arguments[0].value = arguments[1]", element, value); } 

并使用它:

 WebElement inputField = driver.findElement(By...); setValue(inputField, "The long long long long long long long text......"); 

另请参阅使用Python在Selenium WebDriver测试中不要加载图像和在Firefox上渲染CSS

隐藏CSS和图像:

 FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("permissions.default.stylesheet", 2); profile.setPreference("permissions.default.image", 2); FirefoxDriver browser = new FirefoxDriver(profile); 

您也可以使用PhantomJS是没有用户界面的WebKit浏览器,因此它比FireFox或Chrome更快。 PhantomJS支持Web驱动程序。