Selenium 中的 HTMLUnitDriver

无头浏览器是没有图形用户界面的网络浏览器。它可以在后台运行,没有视觉干扰。它提供了一种高效且有效的方式来测试网络应用程序,同时节省时间和资源。在本教程中,我们将深入探讨什么是无头浏览器,何时使用无头浏览器测试,以及如何使用 Selenium 执行它。

什么是无头浏览器?

无头浏览器是一种没有图形用户界面的网络浏览器。这个程序将像浏览器一样运行,但不会显示任何图形用户界面。

无头驱动的一些示例包括

  • HtmlUnit
  • Ghost
  • PhantomJS
  • ZombieJS
  • Watir-webdriver

何时使用无头浏览器测试?

在当今的数字时代,网络应用程序被开发成与各种设备和平台兼容。这通常给需要确保其应用程序在这些平台上无缝运行的网站开发者带来了挑战。无头浏览器测试是解决此问题的理想方案,因为它允许开发者在无需图形用户界面的情况下测试其网络应用程序。通过使用无头浏览器测试,开发者可以轻松测试具有多个组件和依赖项的复杂网络应用程序,从而为更快的开发、无错误的代码和满意的用户铺平道路。

使用 Selenium 进行无头浏览器测试

Selenium 是一个用于无头浏览器测试的强大工具,它允许开发者在不需要可见用户界面的情况下运行自动化测试。通过在后台运行测试,Selenium 可以节省时间和资源,同时还能帮助识别在传统基于 UI 的测试环境中可能不明显的问题。这包括性能相关问题和布局问题,这些问题可能只在无头设置中才会显现。然而,重要的是要记住无头测试的局限性,并将其与传统基于 UI 的方法相结合,以确保全面的测试覆盖。

无头浏览器的流行示例

有许多无头浏览器可用,每个都有其独特的特性和优势,使其适用于不同的用例。我们将在下面讨论它们:-

PhantomJS

PhantomJS 是一款无头浏览器,它使用 WebKit 作为其渲染引擎,并支持 HTML5、CSS3 和 JavaScript 等各种网络标准。它可用于屏幕捕获和页面自动化任务。它是开源的,并与多种操作系统兼容。

Python 中使用无头 PhantomJS 的 Selenium 示例

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
# Set up PhantomJS options
phantomjs_options = webdriver.DesiredCapabilities.PHANTOMJS.copy()
phantomjs_options['phantomjs.page.settings.userAgent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
# Set up the PhantomJS driver
driver = webdriver.PhantomJS('/path/to/phantomjs', desired_capabilities=phantomjs_options)
# Perform actions using the driver
driver.get('https://www.example.com')
print(driver.title)
# Close the driver
driver.quit()

Chrome

Chrome 是全球最受欢迎的浏览器,也提供了无头功能。它可以在多个平台上使用,并支持编程语言和框架。其内置的调试工具和详尽的文档使其易于使用,并能解决测试过程中可能出现的任何问题。

Python 中使用无头 Chrome 的 Selenium 示例

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# Set up Chrome options
chrome_options = Options()
chrome_options.add_argument('--headless')  # Run Chrome in headless mode
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
# Set up the Chrome driver
driver = webdriver.Chrome('/path/to/chromedriver', options=chrome_options)
# Perform actions using the driver
driver.get('https://www.example.com')
print(driver.title)
# Close the driver
driver.quit()

火狐浏览器

Firefox 是一种流行的网络浏览器,也可以用作无头浏览器进行测试。使用 Firefox 作为无头浏览器的一大优势是其轻量级特性,使其成为在各种操作系统上进行测试的多功能选项。此外,凭借其详尽的文档和社区支持,Firefox 是那些希望尝试无头浏览器技术的人的绝佳选择。

Python 中使用无头 Firefox 的 Selenium 示例

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
# Set up Firefox options
firefox_options = Options()
firefox_options.add_argument('--headless')  # Run Firefox in headless mode
# Set up the Firefox driver
driver = webdriver.Firefox(options=firefox_options)
# Perform actions using the driver
driver.get('https://www.example.com')
print(driver.title)
# Close the driver
driver.quit()

无头浏览器测试的优点

  • 更快的测试执行
  • 经济高效的测试
  • 更好的测试覆盖率
  • 运行测试的灵活性
  • 与 CI/CD 管道集成

无头浏览器测试的缺点

  • 缺少图形用户界面
  • 调试困难
  • 有限的浏览器支持

HTMLUnitDriver

HTML UnitDriver 是最轻量级、最快的 WebDriver 无头浏览器实现。它基于 HtmlUnit。它被称为无头浏览器驱动程序。它与 Chrome、IE 或 Firefox 驱动程序相同,但它没有 GUI,因此无法在屏幕上看到测试执行。

HTML Unit Driver 的特点

  • 支持 HTTPS 和 HTTP 协议
  • 支持 HTML 响应(点击链接、提交表单、遍历 HTML 文档的 DOM 模型等)
  • 支持 Cookie
  • 代理服务器支持
  • 支持基本和 NTLM 认证
  • 出色的JavaScript支持
  • 支持 GET 和 POST 提交方法
  • 能够自定义发送到服务器的请求头
  • 能够确定服务器的失败响应应该抛出异常还是应该作为适当类型的页面返回

使用 HTMLUnit Driver 和 Selenium 的步骤

步骤 1) 在 Eclipse 中,复制以下代码。将标准 Selenium 库文件添加到项目中。不需要额外的 jar 文件。

package  htmldriver;
import org.openqa.selenium.By;		
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;	
import org.openqa.selenium.htmlunit.HtmlUnitDriver;		
public class htmlUnitYest {				
		public static void main(String[] args) {
                     // Creating a new instance of the HTML unit driver
                      
                     WebDriver driver = new HtmlUnitDriver();
                      
           		     // Navigate to Google		
                     driver.get("http://www.google.com");					
          
					 // Locate the searchbox using its name		
                     WebElement element = driver.findElement(By.name("q"));	
                     
                    // Enter a search query		
                    element.sendKeys("Guru99");	
                   
		            // Submit the query. Webdriver searches for the form using the text input element automatically		
                    // No need to locate/find the submit button		
                    element.submit();			
                    
            		// This code will print the page title		
                    System.out.println("Page title is: " + driver.getTitle());		
                    
                    driver.quit();			
         }		
}

步骤 2) 运行代码。您会观察到没有浏览器启动,结果显示在控制台中。

Steps To Use HTMLUnit Driver with Selenium

Html Unit Driver 的优点

  • 由于它不使用任何 GUI 进行测试,因此您的测试将在后台运行,没有任何视觉中断
  • 与其他所有实例相比,执行速度更快
  • 要通过 HtmlUnit 驱动程序运行测试,您还可以选择其他浏览器版本
  • 它与平台无关,更容易并发运行多个测试。是负载测试的理想选择。

缺点

  • 它无法模拟其他浏览器的 JavaScript 行为

PhantomJS

PhantomJS 是一个带有 JavaScript API 的无头浏览器。它是无头网站测试、访问和操作网页的最佳解决方案,并附带标准 DOM API。

要将 PhantomJS 与 Selenium 结合使用,必须使用 GhostDriver。GhostDriver 是 PhantomJS 中 WebDriver 线协议的简单 JS 实现。

PhantomJS 的最新版本已集成了 GhostDriver,无需单独安装。

系统的工作原理如下:-

PhantomJS

使用 PhatomJS 运行 Selenium 的步骤

步骤 1) 您需要安装了 Selenium 的 Eclipse

步骤 2)此处下载 PhantomJS

Steps To Run Selenium With PhatomJS

步骤 3) 将下载的文件夹解压到 Program Files

Steps To Run Selenium With PhatomJS

步骤 4)此处下载 PhantomJS 驱动程序。将 jar 添加到您的项目中

Steps To Run Selenium With PhatomJS

步骤 5) 将以下代码粘贴到 Eclipse 中

package htmldriver;	
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;	

public class phantom {				
		public static void main(String[] args) {
        	        File file = new File("C:/Program Files/phantomjs-2.0.0-windows/bin/phantomjs.exe");				
                    System.setProperty("phantomjs.binary.path", file.getAbsolutePath());		
                    WebDriver driver = new PhantomJSDriver();	
                    driver.get("http://www.google.com");         
                    WebElement element = driver.findElement(By.name("q"));	
                    element.sendKeys("Guru99");					
                    element.submit();         			
                    System.out.println("Page title is: " + driver.getTitle());		
                    driver.quit();			
           }		
}

步骤 6) 运行代码。您会观察到输出显示在控制台中,并且没有浏览器启动。

注意:首次运行时,根据您的设置,您可能会收到 Windows 的安全警告,要求允许运行 PhantomJS。单击“允许访问”。

Steps To Run Selenium With PhatomJS

许多组织出于各种目的使用 Phantom.JS,例如:

  • 无头测试
  • 屏幕捕获
  • 页面自动化
  • 网络监控
  • 为用户渲染仪表盘截图
  • 在命令行运行单元测试
  • 将 HTML 生成为 PDF 格式的员工手册
  • 与 QUnit 结合用于测试套件

摘要

为了在各种浏览器中快速测试应用程序且没有任何视觉干扰,使用了无头浏览器测试。由于其速度、准确性和易于访问的特性,HTML unit driver 和 PhantomJS 在无头浏览器自动化测试中越来越受欢迎。通过遵循一些简单的步骤,您就可以了解这些工具如何轻松地与其他工具集成并执行测试代码。