65.9K
CodeProject 正在变化。 阅读更多。
Home

10 个高级 WebDriver 技巧和窍门 - 第 1 部分

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (13投票s)

2016年2月14日

Ms-PL

3分钟阅读

viewsIcon

24325

查找一些高级 WebDriver 技巧和窍门,了解如何使用该框架,例如关闭 JavaScript、在无头浏览器中执行测试或使用特定浏览器的配置文件。文章“10 个高级 WebDriver 技巧和窍门(第 1 部分)”最初发表于 Automate The Planet。

引言

正如你可能知道的那样,我正在开发一系列名为 使用 WebDriver 进行实用自动化 的文章。它们包含大量关于如何开始使用 WebDriver 编写自动化测试的实用信息。此外,它们还包含许多更高级的主题,例如自动化策略、基准测试和研究。在接下来的几篇文章中,我将与你分享一些测试中高级 WebDriver 的用法。废话不多说,以下是今天的高级 WebDriver 自动化技巧和窍门。

1. 截取屏幕截图

您可以使用以下方法截取浏览器的全屏截图。

public void TakeFullScreenshot(IWebDriver driver, String filename)
{
    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
    screenshot.SaveAsFile(filename, ImageFormat.Png);
}

有时,您可能需要截取单个元素的屏幕截图。

public void TakeScreenshotOfElement(IWebDriver driver, By by, string fileName)
{
    // 1. Make screenshot of all screen
    var screenshotDriver = driver as ITakesScreenshot;
    Screenshot screenshot = screenshotDriver.GetScreenshot();
    var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));

    // 2. Get screenshot of specific element
    IWebElement element = driver.FindElement(by);
    var cropArea = new Rectangle(element.Location, element.Size);
    var bitmap = bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
    bitmap.Save(fileName);
}

首先,我们截取全屏截图,然后我们通过其位置和大小属性定位指定的元素。之后,找到的矩形块被保存为位图。

以下是如何在测试中使用这两种方法。

[TestMethod]
public void WebDriverAdvancedUsage_TakingFullScrenenScreenshot()
{
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.WaitUntilLoaded();
    string tempFilePath = Path.GetTempFileName().Replace(".tmp", ".png");
    this.TakeFullScreenshot(this.driver, tempFilePath);
}

[TestMethod]
public void WebDriverAdvancedUsage_TakingElementScreenshot()
{
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.WaitUntilLoaded();
    string tempFilePath = Path.GetTempFileName().Replace(".tmp", ".png");
    this.TakeScreenshotOfElement(this.driver, 
    By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div"), tempFilePath);
}

我们通过特殊的 Path .NET 类获取一个临时文件名。 默认情况下,临时文件使用 ".tmp" 扩展名生成,因此我们将其替换为 ".png"。

2. 获取 WebElement 的 HTML 源代码

您可以使用 IWebElement 接口的 GetAttribute 方法获取特定元素的内部 HTML。

[TestMethod]
public void GetHtmlSourceOfWebElement()
{
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.WaitUntilLoaded();
    var element = this.driver.FindElement(By.XPath("//*[@id='tve_editor']/div[2]/div[3]/div/div"));
    string sourceHtml = element.GetAttribute("innerHTML");
    Debug.WriteLine(sourceHtml);
}

3. 执行 JavaScript

您可以使用接口 IJavaScriptExecutor 通过 WebDriver 执行 JavaScript。

[TestMethod]
public void ExecuteJavaScript()
{
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.WaitUntilLoaded();
    IJavaScriptExecutor js = driver as IJavaScriptExecutor;
    string title = (string)js.ExecuteScript("return document.title");
    Debug.WriteLine(title);
}

此测试将通过 JavaScript 获取当前窗口的标题,并将其打印到调试输出窗口。

4. 设置页面加载超时时间

至少有三种方法可用于此任务。

首先,您可以通过 WebDriver 的选项类设置默认驱动程序的页面加载超时时间。

this.driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(0, 0, 10));

您可以通过 JavaScript 等待页面完全加载。

private void WaitUntilLoaded()
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
    wait.Until((x) =>
    {
        return ((IJavaScriptExecutor)this.driver)
        .ExecuteScript("return document.readyState").Equals("complete");
    });
}

您的第三个选择是等待页面上特定元素可见。

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
  By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div")));

Headless Browser

5. 在无头浏览器中执行测试

PhantomJS 是一个无头的 WebKit,可以使用 JavaScript API 编写脚本。它对各种 Web 标准有快速且原生的支持:DOM 处理、CSS 选择器、JSON、Canvas 和 SVG。为了能够在代码中使用 PhantomJSDriver,您首先需要 下载它的二进制文件

[TestMethod]
public void ExecuteInHeadlessBrowser()
{
    this.driver = new PhantomJSDriver(@"D:\Projects\PatternsInAutomation.Tests\WebDriver.Series.Tests\Drivers");
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.WaitUntilLoaded();
    IJavaScriptExecutor js = driver as IJavaScriptExecutor;
    string title = (string)js.ExecuteScript("return document.title");
    Debug.WriteLine(title);
} 

此测试通过 PhantomJSDriver 在 3 秒内执行。 几乎比 FirefoxDriver 快三倍。

6. 检查元素是否可见

您可以使用 IWebElement 接口的 Displayed 属性。

[TestMethod]
public void ExecuteInHeadlessBrowser()
{
    this.driver = new PhantomJSDriver
    (@"D:\Projects\PatternsInAutomation.Tests\WebDriver.Series.Tests\Drivers");
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.WaitUntilLoaded();
    IJavaScriptExecutor js = driver as IJavaScriptExecutor;
    string title = (string)js.ExecuteScript("return document.title");
    Debug.WriteLine(title);
}

7. 使用特定配置文件

默认情况下,如果您使用 FirefoxDriver 的默认构造函数,WebDriver 始终分配一个新的“干净”配置文件。 但是,有时您可能希望微调配置文件,例如添加扩展程序、关闭 JavaScript 等。

FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("YourProfileName");
this.driver = new FirefoxDriver(profile);

您可以为 ChromeDriver 执行一些类似的配置。

ChromeOptions options = new ChromeOptions();
// set some options
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);

8. 关闭 JavaScript

您可以使用第 7 点中的代码来设置新的 Firefox 配置文件。 然后您需要将 'javascript.enabled' 属性设置为 false

FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
profile.SetPreference("javascript.enabled", false);
this.driver = new FirefoxDriver(profile);

Manage Cookies

9. 管理 Cookie

在您可以使用站点的 Cookie 之前,您需要导航到其某些页面。

添加新 Cookie

Cookie cookie = new Cookie("key", "value");
this.driver.Manage().Cookies.AddCookie(cookie);

获取所有 Cookie

var cookies = this.driver.Manage().Cookies.AllCookies;
foreach (var currentCookie in cookies)
{
    Debug.WriteLine(currentCookie.Value);
}

按名称删除 Cookie

this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");

删除所有 Cookie

this.driver.Manage().Cookies.DeleteAllCookies();

按名称获取 Cookie

var myCookie = this.driver.Manage().Cookies.GetCookieNamed("CookieName");
Debug.WriteLine(myCookie.Value);

10. 最大化窗口

使用 IWindow 接口的 Maximize 方法。

[TestMethod]
public void MaximizeWindow()
{
    this.driver.Navigate().GoToUrl(@"http://automatetheplanet.com");
    this.driver.Manage().Window.Maximize();
}

到目前为止,'使用 WebDriver 进行务实的自动化' 系列

© . All rights reserved.