Selenium 简明教程
110+ Selenium Interview Questions and Answers (2024)
Selenium 是用于自动化测试的开源工具。它主要用于测试网络应用程序和自动浏览器交互。与人类用户与浏览器进行交互的方式类似,Selenium 允许与网页进行交互,例如网页导航、输入文本、单击按钮,以及通过创建脚本来验证预期的结果。开发人员可以使用强大的 Selenium 框架跨各种浏览器和平台测试网络应用程序。
Selenium is an open-source tool for automation testing. It is primarily used for testing web applications and automating browser interactions. Similar to how a human user would interact with a browser, Selenium allows interaction with web pages such as web page navigation, entering text, clicking buttons, and validating the expected outcome by creating scripts. Developers can test web applications across various browsers and platforms using the robust Selenium framework.
寻求在 Selenium 方面取得优异成绩的应聘者可以使用这些前 110 个 Selenium interview questions and answers 。无论你是新手还是经验丰富的专业人士,你都可以使用这些问题和解答来测试你的 Selenium 知识以及你批判性思考和解决问题的能力。
Aspirants looking to excel in Selenium can make use of these top 110+ Selenium interview questions and answers. Whether you are a fresher or an experienced professional, you can test your knowledge of Selenium, and your ability to think critically and solve problems with these questions and answers.
Selenium Interview Questions and Answers
以下是关于 Selenium 的最常见的面试问题及解答——
Here is the most frequently asked interview questions and answers on selenium –
1. What is Selenium?
Selenium 是一个免费且开源的 Web 自动化测试工具。它可以用来对网页上的元素执行诸如单击、键入、鼠标和键盘操作等操作,并在执行这些操作后验证生成的结果。
Selenium is a free and open source web automation testing tool. It can be used to perform actions like click, type, mouse and keyboard actions etc on the elements on the web page and validate the outcomes generated after performing them.
Selenium 支持多种语言,即 Java 、 C# 、 Python 、 JavaScript ,并且可以在 Windows、Mac、iPhone 等各种平台上使用。它包括下面列出的工具组——
Selenium supports multiple languages namely Java, C#, Python, JavaScript etc and can be used in various platforms like Windows, Mac, iPhone, etc. It comprises of a group of tools listed below −
2. What are the components of Selenium?
Selenium 是一套工具,由多个工具组成,每个工具用于执行基于网络的测试中的不同项目。Selenium 组件包括——
Selenium is a suite of tools consisting of multiple tools, each of them used to perform various items in web based testing. The Selenium components consist of −
-
Selenium Integrated Development (IDE) − This tool is primarily used for web based testing and popular for the record and playback feature.
-
Selenium Remote Control (RC) − This tool is just like a server and is capable of generating scripts in multiple languages. It takes commands from the tests and directs them to the browser in the form of Selenium core JavaScript commands.
-
Selenium Webdriver − This tool can be used to design test scripts in multiple languages by directly interacting with web browsers
-
Selenium Grid − This tool is used for enabling parallel execution of test scripts on multiple devices, browsers, operating systems etc.
3. What are the advantages we get by using Selenium?
使用 Selenium 的优点如下——
The advantages of using Selenium are listed below −
-
It is open source and does not require any licensing costs.
-
It can be used with multiple browsers like Chrome, Firefox, Safari, Edge etc.
-
It is used to perform testing on various platforms and devices namely, Mac, Windows, iPhones, Androids.
-
It can be integrated with other frameworks like TestNG, Junit etc. Also, it can be used with other build tools, for example Maven, Ant.
-
It can be used to perform headless and parallel execution.
-
It undergoes updates on a regular basis and can be configured very easily. Selenium has a big community support which provides assistance if we are facing issues.
-
It can be used with multiple programming languages like the Java, JavaScript, C#, Ruby, Python, Kotlin etc.
-
It follows a user-friendly interface which helps the user to create and maintain test scripts.
-
It is not a single tool but a collection of tools each of which can be used for different testing purposes.
4. What are the disadvantages we get by using Selenium?
使用 Selenium 的缺点如下所示:
The disadvantages of using Selenium are listed below −
-
It only supports testing of only web based applications.
-
It requires technical knowledge and coding skills.
-
It is not recommended for testing scenarios on barcode, QR scan, captcha etc.
-
It has to be integrated with other tools for report generation.
-
It needs some time prior to being used comfortably with newer versions of browsers and platforms.
-
It does not have any default object repository.
5. What is meant by automation testing and what are its advantages?
自动化测试是借助测试工具将手动测试用例转换为自动化的过程。具有大量重复和冗余步骤的手动测试通常被选为自动化合适的候选者。但是,需要注意的是,不可能将 100% 的手动测试用例自动化。此外,自动化只能在稳定的软件上采用。
Automation testing is the process of converting the manual test cases to automation with the help of testing tools. The manual tests which have a large number of repeated and redundant steps are mostly chosen as the right candidates for automation. However, it must be noted that it is impossible to automate 100% of the manual test cases. Also, automation can be adopted only on a stable software.
自动化测试的优势如下所示:
The advantages of automation testing are listed below −
-
It can be used for verifying both the functional and non-functional requirements of the software.
-
It has a huge return on investment as it saves a lot of time, money, and human effort.
-
Parallel execution can be achieved through automation.
-
It reduces the scope of human error by avoiding manual intervention in executing the test cases.
-
The time saved through automation can be used to manually test very complex scenarios which can not be automated.
-
It lets the testers execute regression and repeated test cases multiple times in a test cycle.
-
It provides faster feedback on how the software is built.
6. Why is Selenium used extensively for automation?
Selenium被广泛用于自动化,因为它与多种浏览器、平台和语言兼容。它不需要任何许可成本。
Selenium is used extensively for automation since it is compatible with multiple browsers, platforms and languages. It does not require any licensing cost.
7. What are known as the Selenese Commands?
Selenese是一组用于执行基于Web的测试的命令。这些命令广泛应用于 Selenium IDE 。 Selenese Commands 有三种类型,即Actions、Accessors和Assertions。
Selenese are a group of commands which are used to perform web based testing. These commands are widely used in Selenium IDE. Selenese Commands are of three types, namely Actions, Accessors, and Assertions.
8. What are the differences between Selenium 3.x and Selenium 4.x?
Selenium的最新版本是4.x版本。该版本的架构和通信符合W3C。Selenium的3.x版本的架构和通信基于JSON Wire协议。Selenium 4.x具有附加的相对定位器,如above()、below()、toRightOf()、toLeftOf()、near(),以及相对定位器的链接。它还提供访问ChromeDevTools,用于调试、网络流量分析以及有助于自动化的其他功能。
The latest version of Selenium is on the version 4.x. The architecture and communication of this version is W3C compliant. The 3.x version of Selenium’s architecture and communication is based on JSON Wire protocol. The Selenium 4.x has additional relative locators like above(), below(), toRightOf(), toLeftOf(), near(), and chaining of relative locators. It also gives access to the ChromeDevTools which are used for debugging, network traffic analysis, and other features that help in automation.
Selenium 3.x扩展了Remote WebDriver,而Selenium 4.x扩展了Chrome Driver。此外,3.x版本需要触发Hub和Node jar来运行Selenium Grid测试,而4.x版本不再需要。Selenium 4.x版本为Chrome和Firefox提供了 Selenium IDE Plugins 。它还附带了Selenium的最新版本的辅助运行器。
The Selenium 3.x extends the Remote WebDriver while the Selenium 4.x extends the Chrome Driver. Besides, the 3.x version needs triggering of Hub and Node jars to run Selenium Grid tests, which is no longer required in the 4.x version. Selenium 4.x version provides Selenium IDE Plugins for Chrome and Firefox. It also comes with the side runner in the latest version of Selenium.
9. What are the differences between Selenium 2 and Selenium 3?
Selenium 2和Selenium 3有什么区别?答:Selenium 3.0是Selenium 2.0的改进版本,并且修复了Selenium 2.0版本的错误。Selenium 2.0是 Selenium RC 和 Selenium Webdriver 的组合。但是,Selenium RC从Selenium 3.0版本开始已不再使用。
What are the differences between Selenium 2 and Selenium 3? Answer: Selenium 3.0 is an improved version of Selenium 2.0 and it has come up with bug fixes of Selenium 2.0 version. Selenium 2.0 was the combination of Selenium RC and Selenium Webdriver. However, Selenium RC became obsolete from the Selenium 3.0 version.
Selenium 2.0没有太大范围的移动测试,但是,从Selenium 3.0开始,移动测试使用 Appium 进行,并且具有比Selenium 2.0更多更新和改进的API。Selenium 2.0现在不再使用。
Selenium 2.0 did not have much scope for mobile testing however from Selenium 3.0 mobile testing is carried out using Appium and it has more updated and improved APIs than Selenium 2.0. Selenium 2.0 is no longer in use now.
10. Name some of the tools used for automation testing
下面列出了一些用于自动化测试的工具:
Some of the tools used for automation testing are listed below −
-
Selenium − It is mainly used for web based automation testing..
-
Cypress − It is mainly used for web based and API automation testing.
-
Playwright − It is mainly used for web based automation testing.
-
Appium − It is mainly used for mobile automation testing.
-
UFT − It is a licensed web automation testing.
-
JMETER − It is mainly used for load testing.
11. What are the various types of locators available in Selenium?
Selenium借助其定位策略来识别网页上的元素。Selenium中提供了以下定位器:
Selenium identifies elements on the web page with the help of its locating strategies. Some of the locators available in Selenium are listed below −
-
Css
-
Xpath
-
Link Text
-
Partial Link Text
-
Id
-
Name
-
Class Name
-
Tagname
从Selenium的最新版本开始,提供了相对定位器,用于根据另一个元素的位置来识别元素。以下是Selenium中的一些 Relative Locators :
From the latest version of Selenium, there are additional locators available called the relative locators which identify elements with respect to the position of another element. Some of Relative Locators in Selenium are listed below −
-
above()
-
below()
-
toRightOf()
-
toLeftOf()
-
near()
-
Chaining of locators
12. What are the different types of testing that can be done using Selenium?
下面列出了可以使用Selenium执行的不同类型的测试:
The different types of testing that can be performed with Selenium are listed below −
-
Regression Testing − This type of testing is performed to verify if code changes have not introduced new bugs in the software.
-
Functional Testing − This type of testing is performed to check if the software is working as per the functional requirements and specifications of the software.
13. What is an Xpath?
xpath 是用于根据其 XML 路径检测元素的查询语言。它用于遍历 XML 文档的 Web 元素及其属性。要获得更多有关 xpath 的信息,请访问以下链接 −
The xpath is a query language used to detect elements depending on its XML path. It is utilized to traverse web elements and their attributes of an XML document. To get more information on xpath, please visit the below link −
14. What is an absolute and relative xpath?
绝对 xpath 由双斜线或//表示。它从文档的起始节点开始识别所需的元素。但是,如果任何元素的路径发生变化(从根节点到当前节点的中间位置),现有的绝对 xpath 将停止识别该特定元素。
The absolute xpath is denoted by the double slash or //. It identifies the desired element starting right from the document’s beginning node. But, if there is a change in path to any element(in between from the root to the current node), the existing absolute xpath will stop working to identify that particular element.
Absolute Xpath Used: /html/body/main/div/div//div/ul/li[2]/input
相对 xpath 由单斜线或/表示。它从 DOM 中的任何位置开始识别所需的元素。
The relative xpath is denoted by the single slash or /. It identifies the desired element starting from anywhere in the DOM.
Relative Xpath Used: //*[@id='gg_bf_1']//parent::ul
15. What are the differences between driver.close() and driver.quit()?
driver.close()用于关闭当前处于焦点的浏览器窗口。如果打开了多个标签和窗口,driver.close()不会关闭所有这些窗口。它只会关闭当前处于活动状态的标签或窗口。如果在驱动程序.close()之后再次调用驱动程序的实例,则将抛出无效会话 ID 的异常。
The driver.close() is used to close the browser window which is presently in focus. In case multiple tabs and windows are opened, the driver.close() will not close all of them. It will only close the tab or the window which is currently active. If the instance of the driver is again invoked after driver.close(), an exception will be thrown on invalid session id.
driver.quit()用于关闭所有打开的窗口和标签,并终止驱动程序会话。如果在驱动程序.quit()之后再次调用驱动程序的实例,则将抛出会话 ID 为 null 的异常。
The driver.quit() is used to close all the opened windows and tabs and terminate the driver session. If the instance of the driver is again invoked after driver.quit(), an exception will be thrown on session id as null.
16. How to wait until a page has been completely loaded using Selenium?
可以使用以下方法在 Selenium 中等待页面完全加载 −
We can wait until a page has been completely loaded using Selenium using the below methods −
Using the Implicit Wait −在此方法中,在每次页面加载时,它将一直等待页面完全加载。
Using the Implicit Wait − In this approach, on every page load it shall wait until the page is completely loaded.
For Example −
For Example −
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Using JavaScript Function −在此方法中,调用 JavaScript 返回 document.readyState,直到在页面加载后返回 complete 为止。
Using JavaScript Function − In this approach, invoke the JavaScript return document.readyState till complete is returned post the page load.
For Example −
For Example −
if (document.readyState == "complete"){
alert("Page is loaded completely");
}
17. What do you mean by exception test in Selenium?
异常测试是一个预测将接收来自测试类的输出的异常的测试。它查找@Test注释,然后查找括号中预期异常的名称。
An exception test is the one which anticipates an exception that will be received as an output from a test class. It looks for the @Test annotation then the name of the expected exception within the brackets.
For Example −
For Example −
@Test
public void test1(expectedException = NoSuchElementException.class){
// description of test method
}
用于不能识别的元素的上述异常测试。
The above exception test for elements which can not be identified.
18. Why is Selenium a popular choice for testing web based applications?
Selenium 是测试基于 Web 的应用程序的流行选择,因为它是一个相对简单的工具,使用 JavaScript 实现。它与多种浏览器、平台和语言兼容。它可以轻松地与其他第三方工具(如 TestNG、Junit、Maven 等)集成。
Selenium is a popular choice for testing web based applications because it is a relatively easy tool which is implemented using JavaScript. It is compatible with multiple browsers, platforms, and languages. It can be easily integrated with other third party tools like TestNG, Junit, Maven etc.
19. Name the various annotations used along with Selenium
与 Selenium 一起使用的各种注释通常是 TestNG 测试自动化框架的一部分。下面列出了与 Selenium 一起使用的一些注释 −
The various annotations which are used along with the Selenium are usually a part of the TestNG test automation framework. Some of annotations used along with the Selenium are listed below −
-
@BeforeSuite
-
@AfterSuite
-
@BeforeClass
-
@AfterClass
-
@BeforeSuite
-
@AfterSuite
-
@BeforeTest
-
@AfterTest
20. What is known as TestNG in Selenium?
TestNG 是可与 Selenium 集成的单元测试自动化框架。它支持对测试进行分组、设置优先级、并行测试等。
TestNG is a unit test automation framework which can be integrated with Selenium. It enables the use of grouping tests, setting priority to them, parallel testing etc.
21. What is the same-origin policy?
同源策略是应用于浏览器的安全特性,它不允许一个源的文档或脚本访问另一个源的文档或脚本。它包括协议、起源和端口。
The same-origin policy is a security characteristic applied on browsers that does not allow a document or script belonging to one origin to be accessible to a document or script of another origin. It comprises protocol, origin and port.
因此,如果 web 浏览器的两个脚本都来自类似的源,那么它允许特定 web 页面的脚本访问另一个 web 页面。同源策略保护网页的安全数据免受来自不同来源的另一个网页的恶意攻击。
Thus a web browser enables scripts from a particular web page to approach another web page if both of them are from a similar origin. The same-origin policy protects a web page’s secured data from the malicious attack from another web page from a different origin.
为了避免同源政策,采用了代理注入技术。在这种方法中,Selenium 服务器充当客户端配置的 HTTP 代理,并欺骗浏览器接受 Selenium Core 和被测应用程序属于同源。
To avoid the same-origin policy, the proxy injection technique is adopted. In this method, the Selenium server conducts as a client configured HTTP proxy and tricks the browser into accepting that the Selenium Core and the application under test belong to the same origin.
22. Why is Selenium chosen before UFT?
由于以下原因,Selenium 通常比 UFT 更受欢迎 −
Selenium is mostly chosen over UFT because of the reasons listed below −
-
UFT is a licensed tool and it comes with a cost, whereas Selenium is free and open source.
-
UFT is used to test only the windows applications, whereas the Selenium can test on multiple platforms like Windows, Linus, Mac, iPhone, Blueberry etc.
-
UFT is a desktop application while Selenium is a collection of APIs.
-
UFT is only supported with Visual Basic scripting, whereas the Selenium works with multiple programming languages like Java, C#, Python, JavaScript, Ruby, Kotlin etc.
-
If the testing team is looking for a free, open source tool and is well equipped with the programming languages, then Selenium is always the better choice than UFT. However, if the testing team is only aware of VB scripting and requirement is to verify in the Windows platform, then UFT can be chosen.
23. What is POM or Page Object Model and what are its benefits?
POM 也称为 Page Object Model 是一个设计模式,该模式通过将元素和测试用例流分离到各个类文件中,可用于创建 Selenium 测试脚本。POM 的优势在于它通过将 Web 元素与测试用例分离,增强了代码的可读性、可重复利用性和易于维护性。
POM also known as Page Object Model is a design pattern that can be used to create Selenium test scripts by separating the elements and test case flows into individual class files. The benefits of POM are that by separating the web elements and the test cases, it gives more code readability, reusability, and easy maintenance.
24. What are the different types of waits available in Selenium?
以下是 Selenium 中可用的不同类型的等待:
The different types of waits available in Selenium are listed below −
此类型为默认类型,其中 Selenium 在抛出异常之前等待特定的时间量。
It is of default type where the Selenium waits for a specific amount of time prior to throwing an exception.
For Example −
For Example −
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
此等待用于告知 Webdriver 在抛出异常之前按特定的条件等待给定的时间量。
This wait is used to inform the Webdriver to wait for a specific condition for the given amount of time prior to throwing an exception.
For Example −
For Example −
WebDriverWait w = new WebDriverWait(driver, 15);
wt.until(ExpectedConditions.invisibilityOfElementLocated
(By.xpath("//*[@class='btn']")));
此等候用于告知 Webdriver 在给定的间隔中等待特定条件,在此间隔内,针对特定时间量检查该条件,然后再抛出异常。
This wait is used to inform the Webdriver to wait for a specific condition at a given interval during which the condition is checked for a particular amount of time prior to throwing an exception.
For Example −
For Example −
Wait w = new FluentWait(driver).withTimeout(25, TimeUnit.SECONDS)
.pollingEvery(15, TimeUnit.SECONDS)
.ignoring(ElementNotInteractableException.class);
wt.until(ExpectedConditions.titleIs("Online Tutorialspoint"));
25. What are the differences between the findElement() and finElements() methods in Selenium?
以下是 Selenium 中 findElement() 和 finElements() 方法之间的差别:
The differences between the findElement() and finElements() methods in Selenium are listed below −
-
The findElement() returns a WebElement, whereas the findElements() returns the list of WebElement.
-
In case there is no matching element, the findElement() throws NoSuchElementException while the findElements() returns an array list with size 0.
26. What is Selenium Webdriver?
Selenium Webdriver 是 Selenium 套件内的工具集的一部分,可从 Selenium 版本 2 中获得。它可用于使用多种语言、平台和浏览器对 Web 应用程序进行自动化测试。
Selenium Webdriver is a part of the suite of tools within the Selenium available from the Selenium version 2. It can be used to automate tests on web applications using multiple languages, platforms, and browsers.
27. Is Selenium WebDriver a part of the library?
Selenium Webdriver 是一个免费的开源库,用于为基于 Web 的应用程序创建自动化测试脚本。
Selenium Webdriver is a free and open source library used to create automation test scripts for web based applications.
28. What are the different types of navigation commands used in Selenium?
以下是 Selenium 中所用不同类型的导航命令:
The different types of navigation commands used in Selenium are listed below −
driver.navigate().to("url of application") − 它将导航到应用程序的 URL。
driver.navigate().to("url of application") − It will navigate to the application url.
driver.navigate()
.to("https://www.tutorialspoint.com/selenium/practice/login.php");
driver.get("url of application") − 它将启动浏览器以打开应用程序的 URL。
driver.get("url of application") − It will launch the browser to open the application URL.
driver.get("https://www.tutorialspoint.com/selenium/practice/login.php");
driver.navigate().back() − 它将帮助根据浏览器历史记录上下文跳转到上一页。
driver.navigate().back() − It will help to jump to the previous page as per browser history context.
driver.navigate().back();
driver.navigate().forward() - 这将根据浏览历史记录上下文跳转到下一页。
driver.navigate().forward() − It will help to jump forward to the next page as per browser history context.
driver.navigate().forward();
driver.navigate().refresh() - 这将刷新一个网页。
driver.navigate().refresh() − It will reload a web page.
driver.navigate().refresh();
29. What is a data driven framework?
一个 Data Driven 框架是其中测试数据与测试脚本分离。它允许您针对多个数据集执行一个测试用例。此外,如果需要在测试用例中进行更改,可以在不更改测试数据的情况下完成。
A Data Driven framework is one in which the test data is separated from the test script. It allows you to execute a test case against multiple data sets. Also, if there are changes that are required to be made in the test case, those can be done without touching the test data.
30. What all programming languages are supported by Selenium?
Selenium可以与多种编程语言一起使用,如Java,C#,Python,JavaScript,Ruby,Kotlin, Perl 等。
Selenium can be used with multiple programming languages like Java, C#, Python, JavaScript, Ruby, Kotlin, Perl etc.
31. What are the differences between driver.get() and driver.navigate.to()?
以下是driver.get()和driver.naviagte.to()之间的差异:
The differences between driver.get() and driver.naviagte.to() are listed below −
-
The driver.get() method launches a URL and waits for the complete page to load, whereas the driver.naviaget.to() method launches a URL without waiting for the complete page to load.
-
The driver.get() method is a part of the WebDriver interface, whereas the driver.naviaget.to() method is a part of the Navigation interface.
-
The driver.get() method does not allow the browser to move forward or backward to the browser history and its refresh, while the driver.naviaget.to() method allows all these.
32. What scenarios cannot be automated by Selenium?
以下是无法通过Selenium自动执行的场景:
The scenarios which cannot be automated by Selenium are listed below −
-
It cannot automate scenarios consisting of bitmap comparisons.
-
It cannot automate scenarios on captcha.
-
It cannot automate scenarios on bar codes.
-
The performance tests can be automated by Selenium, but it is not the recommended choice to do so.
-
It cannot automate scenarios on video streaming.
33. Name some of the open source frameworks that can be integrated with Selenium
以下列出了一些可以与Selenium集成的开源框架:
Some of the open source frameworks that can be integrated with Selenium are listed below −
34. What will happen when the driver.get() method is used in Selenium?
方法driver.get()启动浏览器,打开应用程序URL,并等待整个页面加载。
The method driver.get() launches the browser, opens the application URL these, and waits for the complete page to load.
Syntax
Syntax
driver.get("https://www.tutorialspoint.com/selenium/index.htm");
要获得有关driver.get()的更多信息,请访问链接 Selenium WebDriver Browser Navigation
To get more information on the driver.get(), please visit the link Selenium WebDriver Browser Navigation
35. What is an alternate method to driver.get() method to open an application URL?
driver.get() 方法打开应用程序 URL 的替代方法是 driver.naviaget.to() 方法。它会启动 URL,而无需等待页面完全加载。
The alternate method to driver.get() method to open an application URL is the driver.naviaget.to() method. It launches a URL without waiting for the complete page to load.
Syntax
Syntax
driver.navigate()
.to("https://www.tutorialspoint.com/selenium/index.htm");
36. What is a keyword driven framework?
关键字驱动框架是一种实现逻辑和代码隐藏的框架。它是数据驱动框架的一种扩展。将特定序列中的一组关键字放在 Keyword Driven Framework 中创建测试用例。
A keyword driven framework is the one in which the implementation logic and the code are hidden. It is a kind of extension to the data driven framework. A set of keywords in a specific sequence are placed to create the test cases in a Keyword Driven Framework.
37. How to upload a file using Selenium?
我们可以使用 Selenium 上传文件。如果文件在同一台机器中或放在映射驱动器中,则我们需要将文件的位置传递给 sendKeys() 方法。
We can upload files using Selenium. In case the file is in the same machine or placed in a mapped drive, we would need to pass the location of the file to the sendKeys() method.
Syntax
Syntax
WebDriver driver = new ChromeDriver();
// identify element
WebElement m = driver.findElement(By.xpath("value of xpath locator"));
// obtain file path to be uploaded
File file = new File("./Pictures.png");
System.out.println("File path to be uploaded: " + file.getAbsolutePath());
// uploading file with path
m.sendKeys(file.getAbsolutePath());
38. What are the differences between the getWindowHandle() method and the getWindowHandles() method?
getWindowHandle() 方法和 getWindowHandles() 方法之间的区别如下所示 -
The differences between getWindowHandle() method and getWindowHandles() method are listed below −
-
The getWindowHandles() method returns all the handle ids of the windows and tabs currently opened, whereas the getWindowHandle() method returns the handle id of the window or tab which is in focus.
-
The getWindowHandles() method returns all the handle ids of the windows and tabs currently opened using the Collection Set, while the getWindowHandle() method returns the handle id of the Window or Tab which is in focus as a String.
39. What does WebDriver driver = new FireFoxDriver() mean?
在代码语句 WebDriver driver = new FireFoxDriver() 中,WebDriver 是接口,FirefoxDriver 是类。在这里,我们已借助 Java 中的新关键词创建了 FireFoxDriver 类的对象。然后将该对象分配给 WebDriver Interface 的引用变量 - 驱动程序。
In the code statement, WebDriver driver = new FireFoxDriver(), the WebDriver is an interface and the FirefoxDriver is a class. Here, we have created an object of FireFoxDriver class with the help of the new keyword in Java. Then that object is assigned to the reference variable - driver of the WebDriver Interface.
该语句通常用于代替 FireFoxDriver driver = new FireFoxDriver(),因为在自动化框架中,我们提供了在多个浏览器中执行测试的规定。要实现此功能,只需将浏览器名称传递给可重用方法,然后该可重用方法将创建正确类的对象,并最终将其分配给 WebDriver 接口。
This statement is mostly used in place of FireFoxDriver driver = new FireFoxDriver(), since in automation frameworks, we give the provision to execute tests in multiple browsers. To implement this feature, only the browser name is passed to a reusable method and that reusable method shall create the object of the correct class and finally assign it to the WebDriver interface.
也可以使用语句 FireFoxDriver driver = new FireFoxDriver() 执行相同操作,但是为了优化代码,我们通常使用 WebDriver driver = new FireFoxDriver()。此外,此语句只有使用和调用适用于 Firefox 浏览器的 FireFoxDriver 的方法的选项。
The same can also be done with the statement FireFoxDriver driver = new FireFoxDriver(), however to optimize the code we mostly use WebDriver driver = new FireFoxDriver(). Also, this statement will only have the option to use, and invoke methods of the FireFoxDriver which is applicable for Firefox browser.
我们不能创建特定驱动程序的对象,比如说 FirefoxDriver,然后将其分配给另一个浏览器驱动程序,比如说 ChromeDriver。所以语句 ChromeDriver driver = new FireFoxDriver() 是错误的。但是我们可以将 FirefoxDriver、ChromeDriver 等的对象分配给 WebDriver 接口。语句 WebDriver driver = new WebDriver() 没有用,因为 WebDriver 是接口,而我们不能创建接口的对象。
We cannot create objects of a specific driver, say FirefoxDriver and assign it to another browser driver, say ChromeDriver. So the statement ChromeDriver driver = new FireFoxDriver() is wrong. But we can assign the objects of FirefoxDriver, ChromeDriver, etc to the WebDriver interface. The statement WebDriver driver = new WebDriver() is not used as WebDriver is an interface and we cannot create objects of an interface.
40. Which is the WebDriver’s super interface?
根据类和接口的层次结构,SearchContext 是 WebDriver 的超级接口。Selenium 中类的和接口的层次结构如下图所示 -
As per the hierarchy of the classes and interfaces, the SearchContext is the WebDriver’s super interface. The hierarchy of the classes and interfaces in Selenium is described in the below diagram −
41. How to enter text in a text box in Selenium?
借助以下方法,我们可以在 Selenium 中文本框中输入文本 -
We can enter text in a text box in Selenium with the help of the approaches listed below −
Webdriver driver = new ChromeDriver();
driver.findElement(By.id("value of id")).sendKeys("value to be entered");
Webdriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].setAttribute('value', 'Selenium')", elm);
Webdriver driver = new ChromeDriver();
Actions a = new Actions(driver);
a.sendKeys(e, "value entered").perform();
42. Can we test APIs and webservices using the Selenium?
Selenium 主要用于测试 Web 应用程序,不用于 API Testing 。仅 Selenium 库不能支持 API 或 Web 服务测试,为此需要其他库,例如 Rest Assured。
Selenium is mainly used for testing the web applications and not used for API Testing. Only the Selenium library is not capable of supporting the API or webservices testing, additional library, for example Rest Assured is required for this purpose.
43. Do we need to use the Selenium Server to execute Selenium Webdriver scripts?
Selenium Server 用于执行 Selenium Webdriver 脚本,以借助 Selenium Grid 在多个平台、浏览器和机器中触发并行执行。如果要在远程机器中执行测试,那么需要远程服务器来执行测试脚本。
The Selenium Server is used to execute the Selenium Webdriver scripts to trigger parallel execution among multiple platforms, browsers, and machines with the help of the Selenium Grid. If the tests are to be executed in the remote machine, then the remote server is required to execute the test scripts.
44. What do you mean by WebElement in Selenium?
WebElement 是 Selenium 中的接口,它引用网页上的元素。这用于对页面上的那些元素执行操作。
A WebElement is an interface in Selenium that refers to an element on a web page. This is used to perform actions on those elements on the page.
45. How to move to the nth-child of an element with the help of xpath?
借助以下方法,我们可以通过遵循 xpath 移动到元素的 nth-child -
We can move to the nth-child of an element with the help of the xpath by following the approaches listed below −
Using the xpath expression - //parent/childElement[n]
Using the xpath expression - //parent/childElement[n]
//div/a[5]
以上 xpath 识别的父 div 的第五个锚子级。
The above xpath identifies the fifth anchor child for the parent div.
Using the child axes in xpath expression - //parent/child::tagname[n]
Using the child axes in xpath expression - //parent/child::tagname[n]
Webdriver driver = new ChromeDriver();
WebElement parnt = driver.findElement(By.xpath("//ul[@name='toc']"));
//identify all children nodes with ./child::* expression in xpath
List<WebElement> c = parnt.findElements(By.xpath("./child::*"));
46. Is there an Object Repository in Selenium?
Selenium 中没有默认的对象存储库。但是,所有元素定位器都可以定义在单独的类文件、属性文件等中,以便于维护和从测试用例访问。
There is a no default Object Repository available in Selenium. However, all the elements locators can be defined in separate class files, properties files etc for easy maintenance and access from the test case.
47. How to insert breakpoints in Selenium IDE?
我们在 Selenium IDE 中插入断点以调试测试步骤。可以通过执行以下方法来应用它们:
We insert breakpoints in Selenium IDE to debug test steps. They can be applied by following the methods listed below −
-
Click on the line numbers in the test to add breakpoints.
-
Disable all the breakpoints by pressing Disable breakpoints. The breakpoints get enabled on pressing the same button again.
-
Right clicking on any step, and press Toggle Breakpoint.
48. How to click on a link in Selenium?
借助以下方法列表,我们可以在 Selenium 中单击链接:
We can click on a link in Selenium with the help of the approaches listed below −
Using click() method
Using click() method
Webdriver driver = new ChromeDriver();
driver.findElement(By.linkText("Home")).click();
Using the JavaScript Executor
Using the JavaScript Executor
Webdriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.xpath("//div/ul/li[2]/a"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].click();", elm);
49. How to handle alerts and popups in Selenium?
我们可以在 Selenium 中使用警报接口处理 Alerts and Popups 。最初,驱动程序的焦点在主网页上,要访问警报,我们需要通过 switchTo().alert() 方法将驱动程序的焦点从主网页移到它们。
We can handle Alerts and Popups in Selenium using the Alerts interface. Initially, the driver focus is on the main web page, to access the alerts, we need to shift the driver focus from the main page to them by the switchTo().alert() method.
警报接口的方法如下:
The methods of the Alert interface are listed below −
-
driver.switchTo().alert().accept() − It accepts an alert and clicks on Ok on an alert.
-
driver.switchTo().alert().dismiss() − It dismisses an alert and clicks on Cancel on an alert.
-
driver.switchTo().alert().getText() − It gets the text on an alert box.
-
driver.switchTo().alert().sendKeys("value") − It enters text appearing on a text field on an alert.
50. What are the differences between assert and verify commands in Selenium IDE?
assert 和 verify 命令用于在测试用例中添加验证点。如果 assert 命令中检查的条件不满足,执行将在不匹配处停止。否则,继续执行。如果 verify 命令中检查的条件不满足,执行仍在不匹配处继续。
The assert and verify commands are used to add verification points in the test case. If the condition being checked in an assert command is not satisfied, the execution stops at the point of mismatch. Else the execution is continued. If the condition being checked in a verify command is not satisfied, the execution still continues after the point of mismatch.
51. How to scroll down on a web page in Selenium?
借助 JavaScript Executor,我们可以在 Selenium 中向下滚动网页。要滚动到一定高度,请使用 scrollBy 方法。
We can scroll down on a web page using Selenium with the help of the JavaScript Executor. To scroll down to a certain height, the scrollBy method is used.
Syntax
Syntax
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("window.scrollBy(0,700)", "");
要滚动到页面底部,再次使用 scrollBy 方法。
To scroll down to the bottom of the page, again the scrollBy method is used.
Syntax
Syntax
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript
("window.scrollBy(0,document.body.scrollHeight)");
向下滚动到网页上元素的可见性。
To scroll down to the visibility of an element on the web page.
Syntax
Syntax
WebElement t = driver.findElement
(By.xpath("<value of xpath>"));
// scrolling to view of an element
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].scrollIntoView();", t);
52. What is the difference between getText() and getAttribute() methods in Selenium?
getText() 方法用于获取网页上的元素文本。getAttribute() 方法用于获取 DOM 中元素的运行时值,并且要获取的值作为参数传递。它们两个被称为 WebElement Commands in Selenium 。
The getText() method is used to obtain the element text on a web page. The getAttribute() method is used to get the runtime value of an element in DOM and the value to be obtained is passed as a parameter. Both of them are called the WebElement Commands in Selenium.
Syntax
Syntax
WebDriver driver = new ChromeDriver();
// Identify the element
WebElement elm = driver.findElement
(By.xpath("<value of xpath>"));
// text of the element
String text = elm.getText());
// Identify another element
WebElement elm1 = driver.findElement
(By.xpath("<value of id>"));
// enter text in input box
elm1.sendKeys("Selenium Interview");
// Obtain the value entered
String text = elm1.getAttribute("value");
53. How to get a css property of an element?
我们可以用 getCSSValue() 方法获取元素的 css 属性。如果要获取颜色或边框颜色等 css 属性,我们需要将其作为参数传递给这个方法。
We can get a css property of an element using the getCSSValue() method. To get the css properties like color or border-color, we need to pass them as the parameters to this method.
Syntax
Syntax
WebDriver driver = new ChromeDriver();
// Identify the element
WebElement element = driver.findElement
(By.xpath("<value of xpath>"));
// Get background color
String color = element.getCssValue("background-color"));
54. What is the use of @FindBy annotation in Page Factory?
Page Factory 中的 @FindBy 注解用于标识、声明并在网页上使用定位符(如 xpath、css、tagname、链接文本、部分链接文本、name、类名等)对网页元素执行操作。
The @FindBy annotation in Page Factory is used to identify, declare and do actions on the web elements using locators like xpath, css, tagname, link text, partial link text, name, class name etc on a web page.
Syntax
Syntax
FindBy(id = "name")
WebElement elm;
55. What do you mean by the Hybrid framework?
混合框架是结合了数据驱动框架和关键字驱动框架特性的框架。使用 Hybrid Framework 构建的测试脚本更健壮,并且更容易维护。
The hybrid framework is the one which combines the features of both the data driven and keyword driven frameworks. The test scripts built using the Hybrid Framework are more robust, and are found to be more easy to maintain.
56. How to handle frames in Selenium?
我们可以在 Selenium 中处理框架。最初,驱动的焦点在主网页上,为了访问框架,我们需要通过 switchTo().frame() 方法将驱动焦点从主页面切换到框架。
We can handle frames in Selenium. Initially, the driver focus is on the main web page, to access the frames, we need to shift the driver focus from the main page to the frames by the switchTo().frame() method.
以下是框架中的一些基本重载方法:
Some basic overloaded methods on frames are listed below −
switchTo.frame(args) − 将框架索引号作为参数传递。框架的起始索引为零。
switchTo.frame(args) − The frame index number is passed as a parameter. The starting index of the frame is from zero.
driver.switchTo.frame(0), switching to the first frame.
switchTo.frame(args) − 将框架 id 或 name 作为参数传递。
switchTo.frame(args) − The frame id or name is passed as a parameter.
driver.switchTo.frame(“id-value”), switching to the frame
having id or name value as id-value.
switchTo.frame(args) − 将框架 webelement 作为参数传递。
switchTo.frame(args) − The frame webelement is is passed as a parameter.
driver.switchTo.frame(“id-name”), switching to the frame
having webelement value as id-name.
driver.switchTo.defaultContent() − 将驱动上下文从框架切换回主页面。
driver.switchTo.defaultContent() − To switch driver context from the frame to the main page.
57. How to clear a text from an input box in Selenium?
我们可以使用 clear() 方法来清除 Input Box in Selenium 中的文本。首先,使用 sendKeys() 将文本输入输入框,然后借助 clear() 方法清除文本。
We can clear a text from an Input Box in Selenium using the clear() method. At first the text is entered in an input box using the sendKeys() and then cleared by taking help of the clear() method.
58. How to get the value of an element attribute in Selenium?
我们可以使用 getAttribute() 方法获取 Selenium 中元素属性的值。例如,我们可以使用 getAttribute() 方法获取在文本框中输入的值,然后将值作为参数传递给该方法。
We can get the value of an element attribute in Selenium by using the getAttribute() method. For example, we can obtain the value entered in a text box using the getAttribute() method and then pass value as a parameter to that method.
Syntax
Syntax
// Identify element
WebElement textBox = driver.findElement
(By.className("<value of class name>"));
// Enter text in text box
textBox.sendKeys("Interview Questions");
// Obtain the value entered
String text1 = textBox.getAttribute("value");
59. How to submit a form in Selenium?
我们可以使用 Selenium 提交 form 。表单元素的标签名是 form,其类型属性的值等于提交。我们可以采用以下方法提交表单:
We can submit a form using Selenium. The form elements have the tagname as form and the value of its type attribute is equal to submit. To submit a form we can take up the approaches listed below −
WebDriver driver = new ChromeDriver();
// Identify element within form
WebElement inputBox = driver.findElement
(By.xpath("<value of xpath>"));
inputBox.sendKeys("Name");
// Submitting form with submit()
WebElement button = driver.findElement
(By.xpath("<value of xpath>"));
button.submit();
WebDriver driver = new ChromeDriver();
// Identify element within form
WebElement inputBox = driver.findElement
(By.xpath("<value of xpath>"));
inputBox.sendKeys("Name");
// Submitting form with click()
WebElement button = driver.findElement
(By.xpath("<value of xpath>"));
button.click();
60. What is the architecture of Selenium Webdriver?
Selenium Webdriver 在其最新版本 4.x 中的架构完全基于 W3C WebDriver 协议。以前,客户端到服务器的 HTTP 请求和响应是由 JSON Wire 协议执行的。但是,从 4.x 版本开始,Selenium 客户端库与浏览器驱动的通信是通过 W3C WebDriver 协议进行的。
The architecture of the Selenium Webdriver in its latest version of 4.x is completely on W3C WebDriver protocol. Earlier the HTTP requests and response from the client to the server was carried out by JSON Wire Protocol. However, from the version 4.x, the communication of the Selenium client library to the browser drivers is done via the W3C WebDriver protocol.
Web 浏览器及其驱动程序已经符合 W3C,因此 Selenium Webdriver 采用了相同的协议,以便在整个架构中遵循标准且通用的协议。它还为测试带来了稳定性,并且可以为多个浏览器使用通用代码。此外,Selenium 中现在使用的 Actions API 提供了其他功能,例如双击键盘、放大/缩小等。
The web browsers and their drivers were already W3C compliant, so the Selenium Webdriver adopted the same protocol so that a standard and common protocol is followed in the entire architecture. It also brings stability to the tests and common code can be used for multiple browsers. Besides the Actions API used in Selenium now provides additional features like two key press, zoom in/out etc.
61. Name some of the exceptions faced in Selenium Webdriver
在使用 Selenium 时,我们会遇到许多异常。当找不到元素,或者预期与实际结果不匹配时,或者由于其他任何原因,就会发生异常。该代码生成一个异常,以合乎逻辑的方式结束测试。
While working with Selenium we face numerous exceptions. An exception occurs when an element is not found or if there is a mismatch between the expected and actual outcome, or for any other reasons. The code generates an exception to end the test in a logical way.
62. Name some of the commonly used automation testing tools used for non-functional testing
用于非功能测试的常用 automation testing tools 如下所列:
The commonly used automation testing tools used for non-functional testing are listed below −
-
LoadRunner
-
JMeter
-
Silk Performer
-
Gatling
-
Apache
-
Neoload
63. What is the difference between / and // in xpath locator?
单斜杠或 / 表示绝对 xpath,双斜杠或 // 表示相对 xpath。绝对路径从根节点开始定位元素,而相对路径从 DOM 中的任意位置开始标识元素。
The single slash or / refers to the absolute xpath and the double slash or // refers to the relative xpath. The absolute path starts from the root node to locate an element while the relative path starts from anywhere in the DOM to identify an element.
Absolute Xpath Used: /html/body/main/div/div/ul/li[3]/a
Relative Xpath Used: //ul[@id='bn_jn_w']//child::li[3]/a
64. Name the various types of Webdriver API used in Selenium
Selenium 中使用的各种 Webdriver API 类型如下所列:
The various types of Webdriver API used in Selenium are listed below −
-
ChromeDriver
-
FirefoxDriver
-
InternetExplorerDriver
-
HTMLUnitDriver
-
SafariDriver
-
iPhoneDriver
-
RemoteWebDriver
-
AndroidDriver
-
iPhoneSimulatorDriver
-
EventFiringWebDriver
65. How to handle the synchronization problems in Selenium?
我们可以通过对测试应用隐式、显式和流畅的等待来处理 Selenium 中的不同同步问题。这些是合并到测试中的等待,以便 Selenium 工具及其与 Web 元素的交互并行进行,并且这两个实体之间没有延迟。
We can handle different synchronization problems in Selenium by applying the implicit, explicit, and fluent waits on the tests. These are waits incorporated in the tests so that the Selenium tools and its interaction with the web elements happen in parallel and there is no delay between the two entities.
66. Write the code to launch an application in the Chrome browser.
在 Chrome 浏览器中启动应用程序的代码如下 −
The code to launch an application in the Chrome browser is given below −
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LaunchChromeBrowser {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/radio-button.php");
System.out.println("Get the page URL: " + driver.getTitle());
// Closing browser
driver.quit();
}
}
67. Write the code to launch an application in the Firefox browser
在 Firefox 浏览器中启动应用程序的代码如下 −
The code to launch an application in the Firefox browser is given below −
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LaunchFirefoxBrowser {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new FirefoxDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/radio-button.php");
System.out.println("Get the page URL: " + driver.getTitle());
// Closing browser
driver.close();
}
}
68. How to get the text of an element in Selenium?
我们可以使用 getText() 方法在 Selenium 中获取元素文本。
We can get the text of an element in Selenium by using the getText() method.
Syntax
Syntax
// Identify element
WebElement textBox = driver.findElement
(By.className("<value of class name>"));
// Obtain the text
String text1 = textBox.getText();
69. Can we test the mobile applications using Selenium Webdriver?
我们无法使用 Selenium Webdriver 测试移动应用程序。我们通常使用建立在 Selenium 之上的 Appium 对其进行测试。
No we cannot test the mobile applications using the Selenium Webdriver. We test them normally using the Appium which is built on the top of Selenium.
70. How to perform the drag and drop operations in Selenium?
我们可以在 Selenium 中使用 Actions 类的方法 dragAndDrop() 和 dragAndDropBy() 执行 drag and drop 操作。dragAndDrop 方法有两个参数——源位置和目标位置。dragAndDropBy 方法有三个参数——源位置、水平方向的 X 偏移值以及垂直方向的 Y 偏移值。
We can perform the drag and drop operations in Selenium with the help of the methods - dragAndDrop() and dragAndDropBy() of the Actions class. The dragAndDrop method has two parameters - source and destination locators. The dragAndDropBy method has three parameters - source locator, x offset value in horizontal direction, and y offset value in vertical direction.
71. How to handle cookies in Selenium?
我们可以在 Selenium 中处理 cookies 。我们可以获取、添加以及删除 cookie。下面列出了 cookie 的基本方法 −
We can handle cookies in Selenium. We can get, add, and delete cookies. The basic methods on cookies are listed below −
-
addCookie() − It adds a cookie to the current session.
-
getCookieNamed() − It gets a cookie with a specific name among all the created cookies.
-
getCookies() − It gets all the cookies for the current session.
-
deleteCookieNamed() − It deletes a cookie with a particular name, passed as a parameter.
-
deleteCookie() − It deletes a cookie with the cookie object, passed as a parameter.
-
deleteAllCookies() − It deletes all cookies from the current browser session.
72. How to handle multiple windows in Selenium?
我们可以在 Selenium 中处理 multiple windows 。最初,驱动程序焦点处在主窗口上,要访问其他窗口,我们需要将驱动程序焦点从主窗口切换到其他窗口,方法是使用 switchTo().window("子窗口句柄 ID") 方法。
We can handle multiple windows in Selenium. Initially, the driver focus is on the main window, to access the other window, we need to shift the driver focus from the main window to the other by using the switchTo().window("child window handle id") method.
与窗口交互的方法如下 −
The methods to interact with windows are listed below −
-
getWindowHandles() it returns the handle ids of all the windows currently opened using the Collection Set.
-
The getWindowHandle() method returns the handle id of the window which is in focus as a String.
73. How to enter text in a text box without using the sendKeys() method in Selenium?
我们可以不使用 sendKeys() 方法而输入文本框中的文本。这也可以使用 JavaScript Executor 来完成。
We can enter text in a text box without using the sendKeys() method. This can also be done with the JavaScript Executor.
Syntax
Syntax
Webdriver driver = new ChromeDriver();
WebElement element = driver.findElement(By.name("value of name"));
JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript("arguments[0].setAttribute('value', 'Interview')", element);
74. How to perform mouse hover actions in Selenium?
我们可以使用 Actions Class 的 moveToElement() 方法在 Selenium 中执行鼠标悬停操作。
We can perform mouse hover actions in Selenium with the help of the moveToElement() method of the Actions Class.
Syntax
Syntax
WebDriver driver = new ChromeDriver();
// identify element
WebElement m1 = driver.findElement
(By.xpath("//div/div[3]/nav/div/a"));
Actions actions = new Actions(driver);
actions.moveToElement(m1).click().build().perform();
75. What is Page Factory?
Page Factory 是一个类,有助于实现页面对象模型。它是页面对象模型的扩展,并且可从 WebDriver 类获得。
The Page Factory is a class which assists in implementing the Page Object Model. It is an extension of the Page Object Model and is available from the WebDriver class.
76. How to select an option in the dropdown in Selenium?
我们可以使用 Select 类的以下方法在下拉列表中选择一个选项。网页中的下拉列表以 select 标签名表示,其选项以 options 标签名表示。Selenium Webdriver 中有多个 Select 类方法。它们如下所示:
We can select an option in the dropdown using the methods of the Select class. The dropdowns in a web page are represented by select tagname and its options are represented by the options tagname. There are multiple Select class methods in Selenium Webdriver. They are listed below −
getOptions() − 它返回所有选项的列表。
getOptions() − It returns the list of all the options.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
List<WebElement> elm1 = sel.getOptions();
getFirstSelectedOption() − 它返回下拉列表中选定的选项。
getFirstSelectedOption() − It returns the selected option in the dropdown.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
options = sel.getFirstSelectedOption();
isMultiple() − 如果下拉列表允许多项选择,则返回 true 值。
isMultiple() − Returns a true value if the dropdown allows selection of multiple items.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
boolean result = sel.isMultiple();
selectByIndex() − 要选择的下拉列表选项的索引作为参数传递。索引从 0 开始。
selectByIndex() − The index of the option of the dropdown to be selected is passed as a parameter. The index starts from 0.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.selectByIndex(0);
selectByValue() − 要选择的下拉列表选项的值属性作为参数传递。
selectByValue() − The value attribute of the option of dropdown to be selected is passed as a parameter.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.selectByValue("option 5");
selectByVisibleText() − 要选择的下拉列表选项的可见文本作为参数传递。
selectByVisibleText() − The visible text of the option of the dropdown to be selected is passed as a parameter.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.selectByVisibleText("Interview");
deselectByVisibleText() − 要取消选择的下拉列表选项的可见文本作为参数传递。
deselectByVisibleText() − The visible text of the option of the dropdown to be deselected is passed as a parameter.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.deselectByVisibleText("Interview");
deselectByValue() − 要取消选择的下拉列表选项的值属性作为参数传递。
deselectByValue() − The value attribute of the option of the dropdown to be deselected is passed as a parameter.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.deselectByValue("option 5");
deselectByIndex() − 要取消选择的下拉列表选项的索引作为参数传递。
deselectByIndex() − The index of the option of the dropdown to be deselected is passed as a parameter.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.deselectByIndex(0);
deselectAll() − 取消选择所有已选择的选项。
deselectAll() − unselects all selected options.
WebDriver driver = new ChromeDriver();
WebElement elm = driver.findElement(By.id("value of id”))
Select sel = new Select(elm);
sel.deselectAll();
getAllSelectedOptions() − 返回所有已选择的选项。
getAllSelectedOptions() − returns all the selected options.
77. How to work with hidden elements in Selenium?
我们可以借助 JavaScript Executor 在 Selenium 中使用隐藏元素
We can work with hidden elements in Selenium with the help of the JavaScript Executor
Syntax
Syntax
WebDriver driver = new ChromeDriver();
// Javascript executor class
JavascriptExecutor j = (JavascriptExecutor) driver;
// identify hidden element and set value
j.executeScript
("document.getElementById('hidden-field').value='Interview';");
String st = (String) j.executeScript("return
document.getElementById('hidden-field').value");
78. What happens when you use both Thread.sleep() and Webdriver waits in Selenium?
Thread.sleep() 会将测试执行停止特定时间,Webdriver 也将等待直到满足条件为止。如果我们同时使用这两个等待,它会增加整体执行时间。
The Thread.sleep() stops the test execution for a specific amount of time and the Webdriver waits also to hold the execution for a specific amount of time till a condition is met. If we are using both the waits, it will increase the overall execution time.
79. What happens when you use both implicit and explicit waits in Selenium?
不建议在同一 Selenium 测试中添加两个 implicit and explicit waits 。在同一个驱动程序会话中添加它们时,会导致不确定的等待时间,例如将显式等待 15 秒和隐式等待 10 秒组合在一起可以在 20 秒后导致超时错误。
It is not recommended to add both the implicit and explicit waits in the same Selenium tests. While adding both of them in one driver session, it results in uncertain wait time, for example having a combination of explicit wait of 15 seconds and implicit wait of 10 seconds can bring a timeout error after 20 seconds.
隐式等待只在测试脚本中使用一次,并且适用于每个测试步骤。然而,显式等待用于等待特定条件。当这两个等待同时应用时,显式等待会覆盖隐式等待。
An implicit wait is used only once in a test script and is applicable to every test step. However, an explicit wait is used to wait for a particular condition. When both the waits are being applied together, the explicit wait overwrites the implicit wait.
80. What is StaleElementReferenceException and avoid to resolve it?
当 Selenium Webdriver 尝试搜索先前可用的 Web 元素而该元素当前不可用或已被从 DOM 中删除时,就会抛出 StaleElementReferenceException。这可能是由于页面刷新或元素或其父级已被移除或删除。因此,当 Webdriver 无法与该元素交互时,就会抛出此异常。
A StaleElementReferenceException is thrown in a scenario where the Selenium Webdriver tries to search a previously available web element which has currently become unavailable or deleted from DOM. This can happen due to a page refresh, or element or its parent has been removed or deleted. Thus this exception is thrown when the Webdriver fails to interact with that element.
可以通过以下列出的措施避免 StaleElementReferenceException:
A StaleElementReferenceException can be avoided by the measures listed below −
-
Refresh the page again
-
Wait for that element
-
Make an attempt to access the same element again
81. How Selenium is used to launch the different browsers?
Selenium 用于启动不同的浏览器,如 Chrome、Firefox、Edge、Safari 等。
Selenium is used to launch different browsers like Chrome, Firefox, Edge, Safari etc.
Syntax
Syntax
// For Chrome
WebDriver driver = new ChromeDriver();
// For Firefox
WebDriver driver = new FirefoxDriver();
// For Edge
WebDriver driver = new EdgeDriver();
// For Safari
WebDriver driver = new SafariDriver();
82. What is an Actions class in Selenium?
Selenium 中的 Actions class 用于执行键盘和鼠标操作。这些操作包括双击、右键单击、单击、按键、拖拽等。Actions 类包括高级用户交互 API。
The Actions class in Selenium is used to carry out keyboards and mouse operations. These include carrying out double click, right click, click, pressing keys, drag and drag actions etc. The Actions class comprises the advanced user interaction APIs.
83. What are the areas where Selenium can contribute more for testing?
Selenium 可用于测试的领域如下所列 −
The areas where Selenium can contribute more for testing are listed below −
-
Mobile Testing
-
Performance Testing
-
API Testing
-
Default generation of reports
-
Visual Testing
-
Cross Browser Testing
84. What is a testng.xml file?
testng.xml 文件是 TestNG 单元测试框架的一部分。它用作配置文件,用于运行 TestNG 测试。借助 testng.xml 文件,可以将测试分组、包含或排除,并行执行等。
The testng.xml file is a part of the TestNG unit testing framework. It is used as a configuration file to run the TestNG tests. The tests can be grouped, included or excluded, executed in parallel etc with the help of the testng.xml file.
85. What are assertions in Selenium?
断言是添加到测试用例中的验证点,用于验证软件是否按预期正确工作。在自动化测试用例中添加断言,以确认测试用例是否通过或失败。断言方法可从 TestNG 和 JUnit 库中获得。
The assertions are verification points added to the test case to verify if the software is working correctly as per the expectations. The assertions are added in the automated test cases to confirm if a test case has passed or failed. The assertion methods are available from the TestNG and the JUnit libraries.
86. How to capture screenshots in Selenium Webdriver?
Selenium WebDriver 用于在测试用例失败时 capture screenshots 。它有助于调试失败的测试步骤。getScreenShotAs 方法是 TakeScreenshot 接口的一部分,用于捕获屏幕截图。
Selenium Webdriver is used to capture screenshots in the event of failure in a test case. It helps to debug a failed test step. The getScreenShotAs method which is a part of the TakeScreenshot interface is used to capture the screenshots.
Syntax
Syntax
Webdriver driver = new ChromeDriver();
WebElement l = driver.findElement(By.id("id"));
l.click();
// take screenshot of link and store in a location
File s = l.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(s, new File("location of screenshot"));
87. How to press the ENTER key within a text box using Selenium?
我们可以使用 sendKeys() 方法和 Key 类在文本框内按 ENTER 键。Keys.ENTER 应作为参数传递给 sendKeys() 方法以执行此操作。
We can press the ENTER key within a text box using the sendKeys() method along with the Key class. The Keys.ENTER is to be passed as a parameter to the sendKeys() method to perform this action.
Syntax
Syntax
WebDriver driver = new ChromeDriver();
// Identify element
WebElement m = driver.findElement(By.name("huj"));
m.sendKeys("Interview");
// Type enter with sendKeys()
m.sendKeys(Keys.ENTER);
88. How to refresh a web page in Selenium?
我们可以在 Selenium 中通过以下列出的不同方式刷新网页 −
We can refresh a web page in Selenium in different ways listed below −
Using the Refresh Method
Using the Refresh Method
driver.get("https://www.tutorialspoint.com/selenium/index.htm");
driver.navigate().refresh();
Using the sendKeys method
Using the sendKeys method
driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
WebElement t = driver.findElement(By.id("fullname"));
t.sendKeys(Keys.F5);
Using the get Method
Using the get Method
driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
driver.get(driver.getCurrentUrl());
Using the navigate.to() method
Using the navigate.to() method
driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
driver.navigate().to(driver.getCurrentUrl());
Using the sendKeys method with ASCII
Using the sendKeys method with ASCII
driver.get("https://www.tutorialspoint.com/selenium/practice/text-box.php");
WebElement t = driver.findElement(By.id("fullname"));
t.sendKeys("\uE035");
89. How to assert the title of a page in Selenium?
我们可以在 TestNG 断言的帮助下断言 Selenium 中页面的标题。
We can assert the title of a page in Selenium with the help of the TestNG assertions.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
public class AssertBrowserTitle {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new FirefoxDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/alerts.php");
System.out.println("Get the page URL: " + driver.getTitle());
// obtain page title and compare
String actTitle = driver.getTitle();
String title = “Selenium Practice - Alerts";
Assert.assertEquals
(actualTitle, expectedTitle);
// Closing browser
driver.close();
}
}
90. Should Selenium be used to verify the captcha?
否,Selenium 不应用于验证验证码。
No Selenium should not be used to verify the captcha.
91. What is a Selenium Maven project?
Selenium Maven 项目是使用 Maven 作为构建工具并获得运行 Selenium 项目的正确依赖关系的项目。它还有助于为源代码、可重用文件、测试代码等创建正确的项目结构。因此,Maven 有助于实现更轻松的代码维护、可读性和可靠性。
A Selenium Maven project is one which uses Maven as a build tool and for getting the correct dependencies to run the Selenium project. It also aids in creating a correct project structure for the source code, reusable files, test code etc. Thus Maven helps to achieve easier code maintenance, readability and reliability.
92. Why is switchTo() method used in Selenium?
switchTo() 方法用于将驱动程序焦点从主页移到另一个窗口、选项卡、警报、框架等。
The switchTo() method is used to shift the driver focus from the main page to another window, tab, alert, frame etc.
93. How to set the browser window size in Selenium?
我们可以使用以下所列方法在 Selenium 中设置浏览器窗口大小 −
We can set the browser window size in Selenium with the help of the approaches listed below −
Using the Maximize Method
Using the Maximize Method
driver.manage().window().maximize();
Using the setSize Method
Using the setSize Method
Dimension dimension = new Dimension(500, 500);
driver.manage().window().setSize(dimension);
Using the JavaScript Executor Method
Using the JavaScript Executor Method
((JavascriptExecutor)driver).executeScript("window.resizeTo(500, 400)");
94. List the automation testing tools which can be integrated with Selenium for continuous integration
下面列出了可与 Selenium 集成以实现持续集成的部分自动化测试工具:
Some of the automation testing tools which can be integrated with Selenium for continuous integration are listed below −
-
Jenkins
-
CircleCI
-
AWS CodePipeline
-
Azure Devops
-
Bit Bucket
95. What is the disadvantage of implicit wait?
隐式等待是一个全局等待,适用于测试用例中的每一步测试。其默认等待时间为 0,会减慢测试执行速度。此外,如果元素在隐式等待中指定时间后被检测到,则可能会导致错误的失败。
The implicit wait is a global wait applied to every test step in a test case. Its default wait time is zero and it slows down the execution of tests. Also, it can cause false failure if the element is detected after the given time specified in the implicit wait.
96. Write the code to launch an application in the Internet Explorer browser
在 InternetExplorer 浏览器中启动应用程序的代码如下:
The code to launch an application in the InternetExplorer browser is given below −
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import java.util.concurrent.TimeUnit;
public class LaunchIEBrowser {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new InternetExplorerDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/modal-dialogs.php");
System.out.println("Get URL: " + driver.getTitle());
// Closing browser
driver.quit();
}
}
97. How to navigate back to the browser in Selenium?
我们可以使用 navigate().back() 方法在 Selenium 中返回浏览器。它有助于浏览器返回浏览器历史记录。
We can navigate back to the browser in Selenium using the navigate().back() method. It helps the browser to shift back to the browser history.
98. Explain the working of the Selenium Grid
Selenium Grid 用于支持跨多个浏览器、平台、设备和计算机的并行执行。它有助于减少执行时间,并且可以通过在多个计算机上分发执行来有效利用资源。它基于集线器-节点架构。
Selenium Grid is used to support parallel execution across multiple browsers, platforms, devices, and machines. It helps to reduce the execution time and allows efficient usage of resources by distributing the execution in multiple machines. It is based on the hub-node architecture.
99. How to identify the dynamic elements in Selenium?
我们可以通过遵循以下列出的方法来识别 Selenium 中的动态元素:
We can identify the dynamic elements in Selenium by following the approaches listed below −
Using Regular Expressions in Locators
Using Regular Expressions in Locators
WebDriver driver = new ChromeDriver();
// identify element with partial class match with * in css
WebElement element =
driver.findElement(By.cssSelector("input[name*='inputTxt']"));
Using Regular Expressions in xpath Locators
Using Regular Expressions in xpath Locators
WebDriver driver = new ChromeDriver();
// Identify element with contains in xpath
WebElement element =
= driver.findElement(By.xpath("//input[contains(@name,'inputTxt')]"))
100. How to set priority to test cases in TestNG?
我们可以通过为具有 @Test 注释的测试方法设置优先级参数来为 TestNG 中的测试用例设置优先级。设置的数字越小,优先级越高。每个测试方法的默认优先级为 0。
We can set priority to test cases in TestNG by setting priority parameters to the test methods having the @Test annotations. The lower the number set, the higher is its priority. The default priority for every test method is 0.
101. How to read data from an excel?
我们可以使用第三方库,即 Apache POI ,从 excel 中读取数据。它有助于在工作簿中的工作表中的行和列中遍历后访问各个单元格。
We can read data from an excel using the third-party library namely, Apache POI. It helps to access individual cells after traversing through the rows and columns within a sheet inside a workbook.
102. How to perform right click in Selenium?
我们可以在 Actions 类的 contextClick() 方法的帮助下对元素执行右键单击。
We can perform a right click on an element with the help of the contextClick() method of the Actions class.
WebDriver driver = new ChromeDriver();
// Identify element
WebElement element = driver.findElement
(By.xpath("//div/div/a"));
Actions actions = new Actions(driver);
actions.moveToElement(element ).contextClick().build().perform();
103. Name the different types of frameworks
下面列出了可用的不同类型的框架:
The different types of frameworks available are listed below −
104. Name different types of listeners in TestNG.
TestNG 中使用的不同类型的侦听器如下所列:
The different types of listeners used in TestNG are listed below −
-
iTestListener
-
IReporter
-
IHookable
-
IExecutionListener
-
IConfugurable
-
IAnnotationTransformer
-
IConfigurationListener
-
IInvokedMethodListener
105. How to handle windows based popup in Selenium?
Selenium 仅用于测试基于网络的应用程序。要处理 Selenium 中基于窗口的弹出窗口,我们必须将 Selenium 与 AutoIt 或 Robot 类集成在一起。
Selenium is used only for testing web based applications. To handle windows based popups in Selenium, we have to integrate Selenium with AutoIt or Robot class.
106. What is the ExpectedConditions class in Selenium?
ExpectedConditions 类是 Selenium 中的一个实用程序类,它提供了在继续下一步之前应该满足的特定条件。这些条件与显式等待一起使用,并有助于实现测试中的同步。ExpectedConditions 类与 WebdriverWait 类一起使用,等待给定条件应在所给时间内得到满足,之后与页面上的 Web 元素的通信再次开始。
The ExpectedConditions class is a utility class in Selenium that gives specific conditions which should be satisfied before moving to the following step. These are used along with the explicit waits and helps to achieve synchronization in tests. The ExpectedConditions class is used along with the WebdriverWait class to wait for a particular time within which the given criteria should be met, after that again the communication begins with the web elements on the page.
Syntax
Syntax
WebDriverWait wt = new WebDriverWait(driver, 15);
wt.until(ExpectedConditions.invisibilityOfElementLocated
(By.id("id value")));
107. How to perform the cross browser testing in Selenium?
Selenium 用于执行 Cross Browser Testing 以验证软件是否与多个浏览器兼容。为此,可以针对不同的浏览器执行相同的测试,以检查是否存在任何问题。在 Selenium 中,跨浏览器测试主要是在 TestNG 单元测试自动化框架的帮助下实现的。
The Cross Browser Testing is performed using Selenium to verify if a software is compatible with multiple browsers. To do so, the same tests are executed against various browsers to check if there are any issues. In Selenium, the cross browser testing is mostly implemented with the help of the TestNG unit test automation framework.
108. How to test the login functionality of an application using Selenium Webdriver?
我们可以使用 Selenium Webdriver 识别应用程序的登录功能。首先,我们必须在浏览器中启动应用程序 URL。然后,我们必须使用 Selenium 中提供的任何定位器(例如 ID、类、名称、css、xpath 等)来识别用户名、密码和登录按钮。最后,我们必须使用 sendKeys() 方法输入用户名和密码,并使用 click() 方法单击登录按钮。
We can identify the login functionality of an application using the Selenium Webdriver. First of all, we have to launch the application URL in a browser. Then we have to identify the username, password, and the login button with the help of any of the locators namely, id, class, name, css, xpath etc available in Selenium. Finally we have to input the username and password with the help of the sendKeys() method and click the login button using the click() method.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import java.util.concurrent.TimeUnit;
public class Login {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new EdgeDriver();
// adding implicit wait of 10 secs
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/login.php");
// identify element
WebElement username = driver.findElement(By.id("email"));
username.sendKeys("Selenium Java");
WebElement password = driver.findElement(By.id("password"));
password.sendKeys("Automation");
// identify element
WebElement loginBtn = driver.findElement
(By.id("//*[@id='signInForm']/div[3]/input"));
loginBtn.click();
// Closing browser
driver.quit();
}
}
109. What is the difference between type and typeAndWait commands in Selenium?
type 命令用于在文本框中输入键盘按键值。它还有助于在组合框中选择一个选项。当我们完成输入并且网页开始加载时,使用 typeAndWait 命令。它会一直等到页面加载完毕再继续执行下一个步骤。
The type command is used to enter keyboard key values in a text box. It also helps to select an option in the combo box. The typeAndWait command is used when we are done with typing and the web page starts loading. It holds back till the page is loaded before moving to the next steps.
110. Describe the usage of Selenium through a test
在开始 Selenium 测试之前,应该满足以下先决条件:
Before starting of a Selenium test, the below prerequisites should be satisfied −
-
Download and Install Java & Maven
-
Download and Install any IDE, say IntelliJ
-
Add the Selenium Dependencies
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FirstTest {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage
driver.get("https://www.tutorialspoint.com/selenium/practice/login.php");
// identify element to enter email address and password
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("Interview");
WebElement p = driver.findElement(By.id("password"));
p.sendKeys("Automation");
// identify login element
WebElement submitBtn = driver.findElement
(By.id("//*[@id='signInForm']/div[3]/input"));
submitBtn.click();
// Closing browser
driver.close();
}
}
111. How to implement the Selenium Webdriver Listeners?
可以通过以下列出的方法实施 Selenium Webdriver 侦听器:
The Selenium Webdriver Listeners can be implemented by the approaches listed below −
-
WebDriverEventListener
-
AbstractWebDriverEventListener
112. How to add a recovery scenario in Selenium Webdriver?
我们可以在 Selenium Webdriver 中通过合并 try-catch 块来添加恢复方案。这是处理代码中异常的一种方法。
We can add a recovery scenario in Selenium Webdriver by incorporating a try-catch block. It is one of the ways to handle exceptions in the code.
Syntax
Syntax
try {
// Perform some tasks
} catch(Exception e1) {
// Code for the catch block
}
113. Is it possible to work with only build() without perform()?
是的,有可能只使用 build() 而不用 perform()。build() 方法构建并返回一个 Actions 类的对象,该对象是一系列操作的集合。如果未使用 build() 方法,则在调用 perform() 时会立即执行操作。
Yes it is possible to work with only build() without perform(). The build() method constructs and returns an object of the Actions class, which is a collection of a series of actions. If the build() method is not used, the actions are done immediately when perform() is called.