This article was originally published on LambdaTest. Thank you for supporting the partners who make SitePoint possible.
本文最初在LambdaTest上发布 。 感谢您支持使SitePoint成为可能的合作伙伴。
Selenium is a popular automation testing framework that is primarily used for cross browser testing. It is open source and is ideal for automating testing of web applications across different browsers like Firefox, Chrome, Internet Explorer, and Microsoft Edge. Selenium has become a renowned framework and is giving stiff competition to other test frameworks such as HP QTP (Quick Test Professional) and AKA HP UFT (Unified Functional Testing). This tutorial for Selenium WebDriver will help you develop a basic understanding of the components of the Selenium suite, the Selenium WebDriver architecture and will show you how to run automation to test a website for cross browser compatibility using Selenium WebDriver for Google Chrome, Mozilla Firefox and Internet Explorer.
Selenium是一种流行的自动化测试框架,主要用于跨浏览器测试 。 它是开源的,非常适合跨Firefox,Chrome,Internet Explorer和Microsoft Edge等不同浏览器自动测试 Web应用程序。 Selenium已成为著名的框架,并且正在与其他测试框架(如HP QTP(快速测试专业版)和AKA HP UFT(统一功能测试))进行激烈竞争。 Selenium WebDriver的本教程将帮助您对Selenium套件的组件,Selenium WebDriver体系结构有基本的了解,并向您展示如何使用Selenium WebDriver for Google Chrome,Mozilla Firefox和Windows XP运行自动化以测试网站是否具有跨浏览器兼容性。 IE浏览器。
Selenium is a combination of different tools and each tool plays a critical role in automating web testing. Let’s dive into the WebDriver tutorial.
Selenium是不同工具的组合,每个工具在自动化Web测试中都扮演着至关重要的角色。 让我们深入了解WebDriver教程。
Below are the core components of the Selenium Test Suite:
以下是Selenium测试套件的核心组件:
Selenium Integrated Development Environment (IDE) Selenium综合开发环境(IDE) Selenium Remote Control (RC) Selenium遥控器(RC) Selenium WebDriver Selenium WebDriver Selenium Grid Selenium网格Now, let’s have a look at these components in details, in this Selenium WebDriver tutorial.
现在,在此Selenium WebDriver教程中,让我们详细了解这些组件。
Selenium IDE is a simple Firefox plugin and it is used to record and playback scripts. However, the Selenium IDE can only be used to write automation scripts for automating testing of simple use cases. Selenium IDE does not support conditional statements, exception handling, loops, screenshot capture, etc. For automating complex use cases, a majority of developers and testers prefer to opt for Scripting testing instead of Record & Replay testing. The Selenium test suite consists of Selenium Remote Control (RC) or Selenium WebDriver.
Selenium IDE是一个简单的Firefox插件,用于记录和回放脚本。 但是,Selenium IDE只能用于编写自动化脚本来自动化简单用例的测试。 Selenium IDE不支持条件语句,异常处理,循环,屏幕截图捕获等。为了自动执行复杂的用例,大多数开发人员和测试人员都喜欢选择脚本测试而不是“记录与重放”测试 。 Selenium测试套件由Selenium远程控制(RC)或Selenium WebDriver组成。
Selenium IDE is available for different operating systems namely Windows, Linux, Mac OS, etc. Selenium IDE for Firefox can be downloaded here.
Selenium IDE适用于Windows,Linux,Mac OS等不同的操作系统。可以在此处下载Firefox的Selenium IDE。
For testing complex scenarios, Selenium Remote Control (RC) can be used. It is based on the client-server model which makes it possible to execute tests on the browser that is controlled by the server. There are client libraries in different programming languages which make it easy for developers to write effective test cases in a programming language in which they are comfortable & have expertise with. Since version 2.25.0, RC has support for Java, C#, Python, Perl, Ruby, etc.
为了测试复杂的场景,可以使用Selenium远程控制(RC)。 它基于客户端-服务器模型,该模型可以在服务器控制的浏览器上执行测试。 客户端库具有不同的编程语言,这使开发人员可以轻松地以他们熟悉且具有专业知识的编程语言编写有效的测试用例 。 从2.25.0版开始,RC支持Java,C#,Python,Perl,Ruby等。
Selenium Server is the core component of the Selenium RC. Some of the core features/responsibilities of the Selenium RC are below:
Selenium Server是Selenium RC的核心组件。 Selenium RC的一些核心功能/职责如下:
Contains the core Selenium Framework and it is mainly responsible for injecting the same in the browser. 包含核心的Selenium Framework,并且主要负责将其注入浏览器。 The client program sends commands to the RC which are then interpreted by the server and then sent to the browser. 客户端程序将命令发送到RC,然后由服务器解释,然后发送到浏览器。 After execution, the results are sent back to the client. 执行后,结果将发送回客户端。 The Client & Server communicate via the normal mechanism of HTTP GETS and POSTs. 客户端和服务器通过HTTP GETS和POST的常规机制进行通信。As mentioned earlier, the Selenium RC supports different browsers, unlike Selenium IDE which is only available for Mozilla Firefox. The downside of Selenium RC is that it does not support record & playback functionality which can be vital in the automation of test cases where tasks are repetitive, especially for regression testing. Before executing the tests using Selenium RC, an instance of the Selenium RC Server should be manually invoked and that instance should be running throughout your entire test cycle.
如前所述,与仅适用于Mozilla Firefox的Selenium IDE不同,Selenium RC支持不同的浏览器。 Selenium RC的缺点是它不支持记录和回放功能,这对于任务重复的测试用例的自动化至关重要,特别是对于回归测试而言 。 在使用Selenium RC执行测试之前,应手动调用Selenium RC Server的实例,并且该实例应在整个测试周期中都在运行。
We know that Selenium IDE is GUI based, where Selenium RC is a standalone Java program that will allow you to execute HTML test suites. The Selenium WebDriver framework is more widely used when compared to Selenium IDE & Selenium RC. Unlike Selenium RC which is based on the client-server model, Selenium WebDriver framework is implemented through a browser-specific driver e.g. each browser will have its corresponding WebDriver application on which the automation testing would be performed.
我们知道Selenium IDE是基于GUI的,其中Selenium RC是一个独立的Java程序,它将允许您执行HTML测试套件。 与Selenium IDE和Selenium RC相比,Selenium WebDriver框架得到更广泛的使用。 与基于客户端-服务器模型的Selenium RC不同,Selenium WebDriver框架是通过特定于浏览器的驱动程序实现的,例如,每个浏览器都有其相应的WebDriver应用程序,将在该应用程序上执行自动化测试。
Selenium WebDriver directly communicates with the browser, so it does not require any separate component like the Selenium Server. It supports top programming languages helpful for a software tester namely C#, Ruby, Java, Python, Perl, etc. Before you go ahead in this Selenium WebDriver tutorial, make sure to download the Selenium WebDriver for the browser on which cross browser testing is being performed. You can download Selenium WebDriver from the links that are mentioned below:
Selenium WebDriver直接与浏览器通信,因此它不需要像Selenium Server这样的任何独立组件。 它支持对软件测试人员有用的顶级编程语言,例如 C#,Ruby,Java,Python,Perl等。在继续执行本Selenium WebDriver教程之前,请确保为正在进行跨浏览器测试的浏览器下载Selenium WebDriver。执行。 您可以从下面提到的链接下载Selenium WebDriver:
Firefox
火狐浏览器
Chrome
Chrome
Internet Explorer
IE浏览器
Microsoft Edge
微软Edge
Serial testing is fine while testing code that is confined to a few browsers, operating systems, or devices. However, the methodology falters once testing has to be performed in an environment that has multiple combinations. This is where parallel testing can be extremely useful, since it can accelerate the whole testing process. Parallel testing can allow you to perform a similar test case across different test configurations, simultaneously. You could also simultaneously execute different test cases in the same browser. There is a lot more to parallel testing, but that may deviate our focus from Selenium WebDriver.
串行测试很好,而测试限于一些浏览器,操作系统或设备中的代码。 但是,一旦必须在具有多个组合的环境中执行测试,该方法就会失败。 这是并行测试非常有用的地方,因为它可以加速整个测试过程。 并行测试可以让您同时在不同的测试配置中执行类似的测试用例。 您也可以在同一浏览器中同时执行不同的测试用例。 并行测试还有很多,但是这可能会偏离我们对Selenium WebDriver的关注。
Back to basics: Selenium Grid is mainly used for parallel testing since it helps run tests on different machines against different browsers & operating systems, simultaneously. It does the job in conjunction with Selenium RC. An example that showcases the usage of Selenium Grid is below:
回到基础:Selenium Grid主要用于并行测试,因为它有助于针对不同的浏览器和操作系统在不同的计算机上同时运行测试。 它与Selenium RC协同工作。 下面是一个展示Selenium Grid用法的示例:
from selenium import webdriver from selenium.webdriver.common.keys import Keys desired_cap = { 'platform' : 'win10', 'browserName' : 'chrome', 'version' : "67.0", } url = "https://username:acsessToken@{LMABDA GRID URL}/wd/hub" driver = webdriver.Remote( desired_capabilities=desired_cap, command_executor= url ) driver.implicitly_wait(1) driver.get("http://www.google.com/") driver.quit()Have a look at the major blocks that comprise the Selenium WebDriver architecture:
看一下构成Selenium WebDriver体系结构的主要块:
Selenium Client Libraries Selenium客户库 JSON Wire Protocol JSON有线协议 Browser Drivers 浏览器驱动程序 Browsers 浏览器Let’s examine each component in more detail.
让我们更详细地检查每个组件。
As mentioned earlier, developers can use Selenium to write test code in different languages like C#, Java, Python, Perl, etc. The multi-language support is possible due to Selenium Client Libraries or Selenium Language Bindings. For example, if you are writing code in Python, you would require Python client libraries. Selenium Client Drivers for different programming languages can be downloaded from here.
如前所述,开发人员可以使用Selenium以不同的语言(例如C#,Java,Python,Perl等)编写测试代码。由于Selenium客户端库或Selenium语言绑定,可以提供多语言支持。 例如,如果您使用Python编写代码,则需要Python客户端库。 可以从此处下载用于不同编程语言的Selenium Client驱动程序。
JSON (JavaScript Object Notation) Wire Protocol facilitates the transfer of data between the Client & Server. It is the REST (Representational State Transfer) based API. Each browser will have its own browser driver.
JSON(JavaScript对象表示法)有线协议简化了客户端与服务器之间的数据传输。 它是基于REST(表示状态传输)的API。 每个浏览器都有自己的浏览器驱动程序。
Browser Driver is mainly used for communicating with the browsers. Since the internal logic of the browser and its functionality is not revealed, Browser Driver ensures the necessary layer of ‘encapsulation’ in order to keep execution level details more abstract. Each browser has its corresponding Browser Driver.
浏览器驱动程序主要用于与浏览器进行通信。 由于未显示浏览器的内部逻辑及其功能,因此浏览器驱动程序可确保必要的“封装”层,以使执行级别的详细信息更加抽象。 每个浏览器都有对应的浏览器驱动程序。
Since Browser Drivers are available for popular browsers like Chrome, Firefox, Internet Explorer, Safari, and Microsoft Edge, you can use any of them for performing cross browser testing. It should be noted that you cannot perform cross browser testing of a website on a browser whose Browser Driver is not publicly available.
由于浏览器驱动程序可用于流行的浏览器,例如Chrome,Firefox,Internet Explorer,Safari和Microsoft Edge,因此您可以使用它们中的任何一个来执行跨浏览器测试。 应当注意,您不能在其浏览器驱动程序不公开的浏览器上对网站执行跨浏览器测试。
LambdaTest offers an on-cloud Selenium Grid to help you fast track your automation testing process. The Selenium Grid offers more than 2000 real browsers and browser versions running on numerous operating systems. You can execute parallel testing using LambdaTest Selenium Grid without worrying about installing any heavy infrastructure on your local machine, plus you get a wide variety of browsers to maximize your test coverage.
LambdaTest提供了一个云端Selenium网格 ,可帮助您快速跟踪自动化测试过程。 Selenium Grid提供了在多种操作系统上运行的2000多种实际浏览器和浏览器版本。 您可以使用LambdaTest Selenium Grid执行并行测试,而不必担心在本地计算机上安装任何繁重的基础架构,此外,您还可以使用各种浏览器来最大化测试范围。
Number of parallel sessions you can run depends entirely on the concurrent sessions you have opted for. Parallel testing can help you trim down your test cycles drastically. For instance, say you have a test suite which takes 60 minutes without parallel testing. Now, if you have 2 concurrencies then you can run 2 tests simultaneously, trimming your total test time to 30 mins. Similarly, if you have 3 concurrencies then the total test time trims further down to 20 minutes. Use LambdaTest concurrency calculator to compute how many concurrent sessions you may need according to your test suite.
您可以运行的并行会话数完全取决于您选择的并发会话。 并行测试可以帮助您大幅缩短测试周期。 例如,假设您有一个测试套件,它需要60分钟才能进行并行测试。 现在,如果您有2个并发,则可以同时运行2个测试,将总测试时间缩短为30分钟。 同样,如果您有3个并发,则总测试时间将进一步缩减至20分钟。 使用LambdaTest 并发计算器 ,根据您的测试套件计算您可能需要多少个并发会话。
Now that you are aware of the basics of Selenium and Browser Drivers, it is time we have a look at a simple WebDriver script. Before we look at the example, please make sure that you have the programming environment ready (we are using Eclipse with all the required packages downloaded from the Eclipse Marketplace). The Selenium Plugin for Eclipse can be downloaded here. The sample code has been written in the Python language, but you can write the test code in C#, Java, Perl, Ruby, etc.
现在您已经了解了Selenium和浏览器驱动程序的基础知识,是时候我们来看看一个简单的WebDriver脚本。 在查看示例之前,请确保已准备好编程环境(我们正在使用Eclipse,并且已从Eclipse Marketplace 下载了所有必需的软件包)。 可以在这里下载Eclipse的Selenium插件。 示例代码已使用Python语言编写,但是您可以使用C#,Java,Perl,Ruby等编写测试代码。
Since the test code will be communicating with the Browser (Chrome, Firefox, Internet Explorer, etc.), please ensure that the corresponding Client Library/WebDriver is installed in your machine. Please refer the section Browser Drivers on how you can download the corresponding WebDriver.
由于测试代码将与浏览器(Chrome,Firefox,Internet Explorer等)通信,因此请确保在您的计算机中安装了相应的客户端库/ WebDriver。 请参阅“浏览器驱动程序”部分,以了解如何下载相应的WebDriver。
Below is a sample code that uses Selenium, Firefox WebDriver to open a webpage:
以下是使用Selenium(Firefox WebDriver)打开网页的示例代码:
# Import the necessary modules for development import time import unit test from selenium import web driver # Invoke a new Firefox Instance ff_driver = webdriver.Firefox() # Blocking wait of 30 seconds in order to locate the element ff_driver.implicitly_wait(30) ff_driver.maximize_window() # Open the required page ff_driver.get("http://www.lambdatest.com") # Sleep for 10 seconds in order to see the results time.sleep(10) # Close the Browser instance ff_driver.close()Let’s walk through the code. Before we perform any action, all the necessary modules are imported using the ‘import’ statement [Lines 2~4]. In the test code, we make use of the Firefox WebDriver since the testing is done against the Firefox Browser [Line 7]. In the code, ff_driver is the WebDriver handle that would be used for performing any interaction with the Firefox browser. In case you do not have the WebDriver installed or you try to use a browser for which there is no support (via WebDriver), it would give the below error:
让我们来看一下代码。 在执行任何操作之前,所有必要的模块都使用' import '语句[第2〜4行] 导入 。 在测试代码中,由于测试是针对Firefox浏览器[第7行]完成的,因此我们使用了Firefox WebDriver。 在代码中, ff_driver是WebDriver句柄,可用于执行与Firefox浏览器的任何交互。 如果您没有安装WebDriver或尝试使用不支持的浏览器(通过WebDriver),则会出现以下错误:
selenium.common.exceptions.WebDriverException: Message: 'operadriver' executable needs to be in PATH.
selenium.common.exceptions.WebDriverException: Message: 'operadriver' executable needs to be in PATH 。
The error message was displayed when we tried to load the WebDriver for Opera browser (without the WebDriver installed on the machine). In order to get rid of the error, you should install the WebDriver for Opera.
当我们尝试加载WebDriver for Opera浏览器(未在计算机上安装WebDriver)时,显示错误消息。 为了摆脱该错误,您应该安装WebDriver for Opera 。
Once all the operations on the Browser are complete, ff_driver.close() is invoked in order to do the necessary cleanup and free up resources.
浏览器上的所有操作完成后,将调用ff_driver.close()进行必要的清理并释放资源。
In order to execute the code, you can invoke Ctrl+F9 in Eclipse IDE or compile the code using Python command line options:
为了执行代码,您可以在Eclipse IDE中调用Ctrl + F9或使用Python命令行选项编译代码:
The previous section in our Selenium WebDriver tutorial, we used the Firefox WebDriver. In this section, we look at the changes that are required in case you are using the Chrome browser for testing. You should ensure that the standalone ChromeDriver binary (which is different than the Chrome browser binary) is available in the right path or it is present as a part of the webdriver.chrome.driver environment variable. If you are using Windows, you need to first download the Chrome WebDriver from here. Paste ChromeDriver.exe in the location where you have installed Python (In our case, it was the default installation path i.e. C:\Python27\Scripts). You have to load the corresponding WebDriver [Line 8] and the rest of the code remains the same. Below is the code snippet, with the change (required for Chrome WebDriver) highlighted in a different colour:
在Selenium WebDriver教程的上一部分中,我们使用了Firefox WebDriver。 在本节中,我们介绍了使用Chrome浏览器进行测试时需要进行的更改。 您应该确保独立的ChromeDriver二进制文件(与Chrome浏览器二进制文件不同)在正确的路径中可用,或者作为webdriver.chrome.driver环境变量的一部分存在。 如果您使用的是Windows,则需要先从此处下载Chrome WebDriver。 将ChromeDriver.exe粘贴到您安装Python的位置(在我们的示例中,这是默认的安装路径,即C:\ Python27 \ Scripts)。 您必须加载相应的WebDriver [第8行],其余代码保持不变。 以下是代码段,其中的更改(Chrome WebDriver要求)以不同的颜色突出显示:
# Import the necessary modules for development import time import unit test from selenium import web driver # Invoke a new Chrome Instance ff_driver = webdriver.Chrome() # Blocking wait of 30 seconds in order to locate the element ff_driver.implicitly_wait(30) ff_driver.maximize_window() # Open the required page ff_driver.get("http://www.lambdatest.com") # Sleep for 10 seconds in order to see the results time.sleep(10) # Close the Browser instance ff_driver.close()So far in our Selenium WebDriver tutorial, we have demonstrated cross browser testing using the Firefox WebDriver & Chrome WebDriver. In this section, we look at the changes that are required in case you are using the Chrome browser for testing. You should download the correct Internet Explorer WebDriver (32 bit/64 bit) from here or here. Paste InternetExplorerDriver.exe in the location where you have installed Python (In our case, it was the default installation path i.e. C:\Python27\Scripts) or any other location of your choice. If you copy the InternetExplorer WebDriver in the path where Python executable is present, you need not to mention the ‘absolute path’ while loading the Web Driver [Line 7]. In the other case, you have to specify the absolute path [Line 9]. Below is the code snippet, with the change (required for IE WebDriver), highlighted in a different colour:
到目前为止,在Selenium WebDriver教程中,我们已经演示了使用Firefox WebDriver和Chrome WebDriver进行跨浏览器测试的过程。 在本节中,我们介绍了使用Chrome浏览器进行测试时需要进行的更改。 您应该从此处或此处下载正确的Internet Explorer WebDriver(32位/ 64位)。 将InternetExplorerDriver.exe粘贴到您安装Python的位置(在我们的示例中,这是默认安装路径,即C:\ Python27 \ Scripts)或您选择的任何其他位置。 如果您在存在Python可执行文件的路径中复制InternetExplorer WebDriver,则在加载Web驱动程序[第7行]时无需提及“绝对路径”。 在其他情况下,您必须指定绝对路径[第9行]。 下面是代码片段,其中的更改(对于IE WebDriver而言是必需的)以不同的颜色突出显示:
# Import the necessary modules for development import time import unit test from selenium import web driver # Method 1 - Invoke a new IE Instance ff_driver = webdriver.Ie() # Method 2 - Invoke a new IE Instance ff_driver = webdriver.Ie("path\to\IEDriverServer.exe") # Blocking wait of 30 seconds in order to locate the element ff_driver.implicitly_wait(30) ff_driver.maximize_window() # Open the required page ff_driver.get("http://www.lambdatest.com") # Sleep for 10 seconds in order to see the results time.sleep(10) # Close the Browser instance ff_driver.close()At last, in our Selenium WebDriver tutorial we will have a look at another example where we make use of ActionChains module which is used to automate low level interactions like mouse movements, button movements, context menu interactions, etc to ensure a robust UI design. More details about ActionChains can be found here.
最后,在我们的Selenium WebDriver教程中,我们将看到另一个示例,其中我们使用ActionChains模块,该模块用于自动化低级交互(例如鼠标移动,按钮移动,上下文菜单交互等)以确保鲁棒的UI设计 。 可以在这里找到有关ActionChains的更多详细信息。
# Import the necessary modules for development import time import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver import ActionChains # Invoke a new Firefox Instance ff_driver = webdriver.Firefox() # Blocking wait of 30 seconds in order to locate the element ff_driver.implicitly_wait(30) ff_driver.maximize_window() # Open the Home Page ff_driver.get("https://www.lambdatest.com/") # Look for the Search Element and enter the Search Criteria search_criteria = ff_driver.find_element_by_link_text("Support") actionChains = ActionChains(ff_driver) actionChains.context_click(search_criteria).perform() time.sleep(5) # Perform action on the Images Link ActionChains(ff_driver) \ .key_down(Keys.CONTROL) \ .click(search_criteria) \ .key_up(Keys.CONTROL) \ .perform() # Sleep for 10 seconds in order to see the results time.sleep(10) # Close the Browser instance ff_driver.close()As seen in the above example code, we retain the code for creating the Firefox WebDriver instance [Lines 9~16]. There are a couple of new modules that are imported – ActionChains and Keys. Once the desired webpage i.e. https://www.lambdatest.com/ is opened by the browser, a search operation is performed by looking at the Link Text (using the find_element_by_link_text method). In our example, the Link Text that is searched on the Web Page is ‘Support’ [Lines 20~22].
如上面的示例代码所示,我们保留了用于创建Firefox WebDriver实例的代码[9-16行]。 导入了几个新模块-ActionChains和Keys 。 一旦浏览器打开了所需的网页(即https://www.lambdatest.com/ ),就可以通过查看链接文本(使用find_element_by_link_text方法)来执行搜索操作。 在我们的示例中,在网页上搜索的链接文本为“支持” [第20至22行]。
Once the Search Criteria is encountered, a (CTRL + CLICK) operation is performed, thereby opening that page in a ‘New Tab’ [Lines 26~30]. The ActionChains module is used for performing that operation. The output is below:
遇到搜索条件后,将执行(CTRL + CLICK)操作,从而在“新建选项卡” [26至30行]中打开该页面。 ActionChains模块用于执行该操作。 输出如下:
We have made use of ActionChains since it was apt for the example which we showcased above. You can have a look at the different modules under Selenium WebDriver module (for Python) here. Though we have used the Python language for implementation, you can make use of the programming language (C#, Java, Perl, Ruby, PHP) of your choice.
我们已经使用了ActionChains,因为它适合我们上面展示的示例。 您可以在此处查看 Selenium WebDriver模块(适用于Python)下的不同模块。 尽管我们使用Python语言来实现,但是您可以使用自己选择的编程语言(C#,Java,Perl,Ruby,PHP)。
Testing using the local WebDriver can be used in case you are planning to test your website on a limited number of ‘browser + operating system + devices’ combination. However, the approach may falter if the number of combinations is more. You cannot have a local setup for every combination since that is not a scalable approach and might also turn out to be very costly.
如果您打算在有限的“浏览器+操作系统+设备”组合中测试网站,则可以使用本地WebDriver进行测试。 但是,如果组合的数量更多,则此方法可能会失败。 您不能为每个组合都设置一个本地设置,因为这不是一种可扩展的方法,而且可能会非常昂贵。
A better solution would be to leverage capabilities of a platform like LambdaTest where you can perform cross-browser testing on the cloud. Using LambdaTest, you can verify your website across 2000+ different browsers, operating systems, and device configurations. To get started, you need to create an account on LambdaTest. Since you would be using Remote WebDriver (using Selenium Grid on LambdaTest) for testing your web application, you should make a note about the username and access key from your LambdaTest profile.
更好的解决方案是利用LambdaTest等平台的功能,在该平台上您可以在云上执行跨浏览器测试。 使用LambdaTest,您可以跨2000多种不同的浏览器,操作系统和设备配置来验证您的网站。 首先,您需要在LambdaTest上创建一个帐户。 由于您将使用远程WebDriver(在LambdaTest上使用Selenium Grid)测试您的Web应用程序,因此应在LambdaTest配置文件中记录用户名和访问密钥。
Now that you know about the usage of Selenium WebDriver and the potential shortcomings of using that approach, we look at how you can port your local WebDriver implementation to Remote WebDriver. The core principles of Remote WebDriver are similar to Local WebDriver, except that the Remote WebDriver code may not execute on the same machine from where it is initiated. Remote WebDriver is based on the client-server model where the server is a simple Java servlet hosted on any modern JEE app server. The Hub/Server loads the tests that have to be executed. It receives test requests from different clients and based on the requirements (termed as desired capabilities), it routes the request to the best-matching/best-fit client.
现在您已经了解了Selenium WebDriver的用法以及使用该方法的潜在缺点,我们将介绍如何将本地WebDriver实现移植到远程WebDriver。 远程WebDriver的核心原理与本地WebDriver相似,不同之处在于远程WebDriver代码可能不在启动它的同一台计算机上执行。 远程WebDriver基于客户端-服务器模型,其中服务器是任何现代JEE应用服务器上托管的简单Java servlet。 集线器/服务器加载必须执行的测试。 它接收来自不同客户端的测试请求,并根据需求(称为所需功能)将请求路由到最匹配/最适合的客户端。
For example, if your test needs to be executed on Ubuntu OS + Chrome, the Server/Hub would scan through the capabilities of the Clients/Nodes registered with the server and divert the request to the Client with matching capabilities. There can be only one server and number of clients in the Selenium Grid architecture. More detailed information about Remote Driver API can be obtained on other blogs on the LambdaTest website.
例如,如果您的测试需要在Ubuntu OS + Chrome上执行,则服务器/集线器将扫描通过服务器注册的客户端/节点的功能,并将请求转移到具有匹配功能的客户端。 在Selenium Grid体系结构中,只能有一个服务器和多个客户端。 可以在LambdaTest网站上的其他博客上获取有关Remote Driver API的更多详细信息。
Once you are logged in to LambdaTest, you should generate the capabilities required by the nodes by visiting LambdaTest Capabilities Generator. Choose your preferred programming language (in our case it is Python) and the appropriate OS/Browser combination. You can enable the Screenshot and Video Recording features while setting the capabilities. As shown below, our requirement is the test should execute on Firefox (version 64.0) which is installed on a Windows 10 machine. The capabilities for the requirement are below:
登录LambdaTest后,您应该通过访问LambdaTest Capabilities Generator来生成节点所需的功能 。 选择您喜欢的编程语言(在我们的例子中是Python)和适当的OS /浏览器组合。 您可以在设置功能时启用屏幕快照和视频录制功能。 如下所示,我们的要求是测试应在Windows 10计算机上安装的Firefox(版本64.0)上执行。 需求的功能如下:
capabilities = { "build" : "Remote WebDriver Testing", "name" : "Remote WebDriver Testing example", "platform" : "Windows 10", "browserName" : "Firefox", "version" : "64.0", }Below is the screenshot from LambdaTest Capabilities Generator:
以下是LambdaTest功能生成器的屏幕截图:
Since we would be using the Selenium Grid on the LambdaTest server, we need to modify our code to access their cloud infrastructure (also termed as Remote URL). The remote URL is shown below:
由于我们将在LambdaTest服务器上使用Selenium Grid,因此我们需要修改代码以访问其云基础架构(也称为远程URL)。 远程URL如下所示:
/* user_name – userid for login on Lambdatest */ /* app_key – Access token obtained from Lambdatest */ remote_url = "https://" + user_name + ":" + app_key + "@hub.lambdatest.com/wd/hub"@hub.lambdatest.com/wd/hub is the Selenium Grid setup on LambdaTest where the test would be executed. For user-authentication purposes, the user_name (used for registration on LambdaTest) & app_key (access-token) are appended to the Grid URL. The concatenated string forms the remote_url. Now that you are aware about the Remote WebDriver API and capabilities generator, let’s port our earlier example to suit these requirements.
@ hub.lambdatest.com / wd / hub是将在LambdaTest上执行测试的Selenium Grid设置。 为了进行用户身份验证,将user_name(用于LambdaTest上的注册)和app_key(访问令牌)附加到网格URL。 串联的字符串形成remote_url。 既然您已经了解了Remote WebDriver API和功能生成器,那么让我们移植我们先前的示例以适合这些要求。
parallel_test_example-1.py
parallel_test_example-1.py
import time import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver import ActionChains import urllib3 #Set capabilities for testing on Firefox ff_caps = { "build" : "Remote WebDriver Testing", "name" : "Remote WebDriver Testing example", "platform" : "Windows 10", "browserName" : "Firefox", "version" : "64.0", } username="<user-name>" accessToken="<access-token>" # gridUrl: gridUrl can be found at automation dashboard gridUrl = "hub.lambdatest.com/wd/hub" url = "https://"+username+":"+accessToken+"@"+gridUrl # Invoke a new Firefox Instance #ff_driver = webdriver.Firefox() urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Porting local webdriver to Remote WebDriver on LambdaTest server ff_driver = webdriver.Remote( command_executor=url, desired_capabilities=ff_caps ) # Blocking wait of 30 seconds in order to locate the element ff_driver.implicitly_wait(30) ff_driver.maximize_window() # Open the Home Page ff_driver.get("https://www.lambdatest.com/") # Look for the Search Element and enter the Search Criteria # We are commenting this code since we are doing basic verification # search_criteria = ff_driver.find_element_by_link_text("Support") # actionChains = ActionChains(ff_driver) # actionChains.context_click(search_criteria).perform() ff_driver.close() ff_driver.quit()Let’s do a code walkthrough, especially the major changes:
让我们进行代码演练,尤其是主要的更改:
The username & accessToken is appended to the gridURL. The combination forms the Remote URL on which the test case execution is performed. 用户名和accessToken附加到gridURL。 组合形成在其上执行测试用例的远程URL。 The webdriver.Remote API is used instead of local WebDriver API. The Remote WebDriver API has two arguments – command_executor : Grid setup on which the test is performed and desired_capabilities : Desired capabilities/requirements of the node. Based on these capabilities requirement, appropriate node is selected on which the code is executed. 使用webdriver.Remote API代替了本地WebDriver API。 远程WebDriver API具有两个参数– command_executor:在其上执行测试的网格设置,以及required_capabilities:节点的所需功能/要求。 根据这些功能要求,选择在其上执行代码的适当节点。In order to check the status of the test, you need to visit your LambdaTest dashboard. You can search the test via its Build-name that is used in formation of the capabilities. A screenshot of the above test being executed on the LambdaTest Grid is below.
为了检查测试的状态,您需要访问LambdaTest仪表板 。 您可以通过其构建名称搜索测试,该构建名称用于形成功能。 下面是在LambdaTest网格上执行的上述测试的屏幕截图。
There are various options on the Output panel that can be instrumental while debugging. Some of the major options are below.
“输出”面板上有多种选项,可在调试时发挥作用。 以下是一些主要选项。
Exception – Lists the exceptions that are encountered during the execution of the test code.
异常 –列出在执行测试代码期间遇到的异常。
Logs – This tab shows the Selenium logs as well as the Console logs. It can be very handy for debugging your code.
日志 –此选项卡显示Selenium日志和控制台日志。 这对于调试代码非常方便。
MetaData – It contains detailed information about the test environment on which the testing was performed. In our case, the test is executed on Firefox 64.0 which is installed on Windows 10 machine. You can even get details about the browser configuration.
元数据 –它包含有关在其上执行测试的测试环境的详细信息。 在我们的案例中,测试是在Windows 10计算机上安装的Firefox 64.0上执行的。 您甚至可以获取有关浏览器配置的详细信息。
One feature on LambdaTest that can accelerate your entire testing process is Parallel Testing. Based on the pricing model that you opt for, you can concurrently execute tests so that the overall test execution time is reduced. In our case, we can have two concurrent sessions. The more concurrent sessions, the shorter the total test execution time.
并行测试是LambdaTest上可以加速整个测试过程的一项功能。 根据您选择的定价模型,您可以同时执行测试,从而减少了总体测试执行时间。 在我们的例子中,我们可以有两个并发会话。 并发会话越多,总测试执行时间越短。
To demonstrate the feature of Parallelization, we perform two test executions in a concurrent fashion. Along with the previous example (parallel_test_example-1.py), we execute the second test (parallel_test_example-2.py) concurrently with it.
为了演示并行化的功能,我们以并发方式执行两个测试执行。 与前面的示例(parallel_test_example-1.py)一起,我们同时执行第二个测试(parallel_test_example-2.py)。
parallel_test_example-2.py
parallel_test_example-2.py
import time import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver import ActionChains import urllib3 #Set capabilities for testing on Chrome ch_caps = { "build" : "Remote WebDriver Testing", "name" : "Remote WebDriver Testing example on Chrome", "platform" : "Windows 10", "browserName" : "Chrome", "version" : "71.0", } username="<user-name>" accessToken="<access-token>" # gridUrl: gridUrl can be found at automation dashboard gridUrl = "hub.lambdatest.com/wd/hub" url = "https://"+username+":"+accessToken+"@"+gridUrl # Invoke a new Firefox Instance #ff_driver = webdriver.Firefox() urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Porting local webdriver to Remote WebDriver on LambdaTest server ff_driver = webdriver.Remote( command_executor=url, desired_capabilities=ch_caps ) # Blocking wait of 30 seconds in order to locate the element ff_driver.implicitly_wait(30) ff_driver.maximize_window() # Open the Home Page ff_driver.get("https://www.lambdatest.com/") # Look for the Search Element and enter the Search Criteria # We are commenting this code since we are doing basic verification # search_criteria = ff_driver.find_element_by_link_text("Support") # actionChains = ActionChains(ff_driver) # actionChains.context_click(search_criteria).perform() ff_driver.close() ff_driver.quit()Execute the two tests in parallel on two different terminals by invoking the python command.
通过调用python命令,在两个不同的终端上并行执行两个测试。
Below is the screenshot from LambdaTest Automation Logs where you can see that there are two tests executing in parallel.
下面是LambdaTest自动化日志的屏幕截图,您可以看到有两个并行执行的测试。
There are number of advantages of using Remote WebDriver API on a cloud infrastructure like LambdaTest since it accelerates the entire testing process. It is also a highly scalable approach. By making use of Concurrency i.e. parallelization, you can further reduce the overall time spent in automation testing.
在LambdaTest之类的云基础架构上使用远程WebDriver API有许多优点,因为它可以加速整个测试过程。 这也是一种高度可扩展的方法。 通过使用并发(即并行化),您可以进一步减少在自动化测试中花费的总时间。
翻译自: https://www.sitepoint.com/how-to-use-selenium-webdriver-for-cross-browser-testing/
相关资源:25个经典网站源代码