If you're looking for Selenium Interview Questions and Answers for Experienced & Freshers, you are at right place. There are a lot of opportunities from many reputed companies in the world. According to research Selenium has a market share of about 27.7%. So, You still have opportunities to move ahead in your career in Selenium. Mindmajix offers advanced Selenium Interview Questions 2020 including selenium IDE, Selenium RC, Selenium Grid and Selenium WebDriver Interview questions that help you in cracking your interview and acquire your dream career as Selenium Developer. 

If you want to become a Selenium Certified Specialist, then visit Mindmajix - A Global online training platform: Selenium Training”.  This course will help you to achieve excellence in this domain.


Below mentioned are the Top Frequently asked Selenium Interview Questions and Answers that will help you to prepare for the Selenium interview. Let's have a look into them.

Frequently Asked Selenium Interview Questions - [Updated 2020]

Top Selenium Interview Questions

Selenium Interview Questions - Basic Level

Q. Selenium Table - Web Tables Information ?
Selenium Table - Web Table Information
Datatype Description Example Default Value
byte It is 4 times small than int, used to save large arrays. byte b=100 0
short It is 2 times small than int, used to save large arrays. short s=1000 0
int Unless memory concern, it is default data type. int q=1000 0
long Larger value than 'int' this is used. int l=100000L oL
char data type charcter is used to store. char a="B" t000'
double Decimal values are stored. int y=0.2345 0.0y
boolean 2 possible ways - T/F values saved. boolean value=true FALSE
float It is used to store arrays of floating values numbers. int q=123.5f 0.0f


Here are the basic level Selenium Interview Questions

1 . What is Selenium ?

Ans: Selenium is one of the most powerful open source automation tool for web application testing (even we can say acceptance testing for the web application) which lets you automate operations like — type, click, the selection from a drop down etc of a web page. Primarily developed in Java Script and browser technologies such as DHTML and Frames and hence supports all the major browsers on all the platforms.

Selenium Online Training Diwali Offer

Want to Add Sparkles to your life ? then just avail this Exclusive Diwali Dhamaka Offer-Get Flat 50% + Additional 20 % Off on Selenium Online Certification Training Course

2. Who developed Selenium Tool and Why ?

Ans: Jason Huggins and team developed this tool in 2004 when they were working for Thought work (IT outsourcing company). They created this tool for the testing of an internal time & expenses application written in (python).

3. How is Selenium different from commercial browser automation tools ?

Ans: Selenium is a library which is available in a gamut of languages i.e. java, C#, python, ruby, php etc while most commercial tools are limited in their capabilities of being able to use just one language. More over many of those tools have their own proprietary language which is of little use outside the domain of those tools. Most commercial tools focus on record and replay while Selenium emphasis on using Selenium IDE (Selenium record and replay) tool only to get acquainted with Selenium working and then move on to more mature Selenium libraries like Remote control (Selenium 1.0) and Web Driver (Selenium 2.o).

Though most commercial tools have built-in capabilities of test reporting, error recovery mechanisms and Selenium does not provide any such features by default. But given the rich set of languages available with Selenium, it very easy to emulate such features.

4. What are the set of tools available with Selenium ?

Ans: Selenium has four set of tools — Selenium IDE, Selenium 1.0 (Selenium RC), Selenium 2.0 (WebDriver) and Selenium Grid. Selenium Core is another tool but since it is available as part of Selenium IDE as well as Selenium 1.o, it is not used in isolation.

5.Which Selenium Tool should I use ?

Ans: It entirely boils down to where you stand today in terms of using Selenium. If you are entirely new to Selenium then you should begin with Selenium IDE to learn Selenium location strategies and then move to Selenium 2 as it is the most stable Selenium library and future of Selenium. Use Selenium Grid when you want to distribute your test across multiple devices. If you are already using Selenium 1.o than you should begin to migrate your test scripts to Selenium 2.0

6. What is Selenium IDE?

Ans: Selenium IDE is a Firefox plug-in which is (by and large)used to record and replay test is Firefox browser. Selenium IDE can be used only with Firefox browser.

7. Which language is used in Selenium IDE?

Ans: Selenium IDE uses html sort of language called Selenese. Though other languages (Java, c#, php etc) cannot be used with Selenium IDE, Selenium IDE lets you convert test in these languages so that they could be used with Selenium 1.0 or Selenium 2.0

8.What is Selenium 1.0 ?

Ans: Selenium 1.0 or Selenium Remote Control (popularly known as Selenium RC) is library available in wide variety of languages. The primary reason of advent of Selenium RC was incapability of Selenium IDE to execute tests in browser other than Selenium IDE and the programmatical limitations of language Selenese used in Selenium IDE.

9. What is Selenium 2.0?

Ans: Selenium 2.0 also known as WebDriver is the latest offering of Selenium. It provides better API than Selenium 1.0 does not suffer from Java script security restriction which Selenium 1.o does supports more UI complicated UI operations like drag and drop.

10. What are the element locators available with Selenium 1.o which could be used to locate elements on web page ?

Ans: There are mainly 4 locators used with Selenium:

  • html id
  • html name
  • XPath locator and
  • Css locators

11. What is Selenium Grid?

Ans: Selenium grid lets you distribute your tests on multiple machines and all of them at the same time. Hence you can execute test on IE on Windows and Safari on Mac machine using the same test script (well, almost always). This greatly helps in reducing the time of test executioin and provides quick feedback to stack holders.helps in reducing the time of test execution and provides quick feedback to stack holders.

12. What is an Accessor in Selenium?

Ans: The accessor is one of the types of Selenese.

1) Accessors are used for storing the value of a target in a variable.


a) storeTitle — Stores the title of a window in a variable
b) storeText — Stores the target element text in a variable

2) Accessors are also used for evaluating the result and storing the result in a variable


a) storeTextPresent — Evaluates whether the text is present in the current window. If the text is present stores true in the variable else stores false
b) store elementPresent — Evaluates whether the element is present in the current window. If the element is present stores true in the variable else stores false.

13. What are two modes of views in Selenium IDE?

Ans: Selenium IDE can be opened either in side bar (View > Side bar > Selenium IDE) or as a pop up window (Tools > Selenium IDE). While using Selenium IDE in browser side bar it cannot record user operations in a pop up window opened by application.

14. Can I control the speed and pause test execution in Selenium IDE?

Ans: Selenium IDE provides a slider with Slow and Fast pointers to control the speed of execution.

15. Where do I see the results of Test Execution in Selenium IDE?

Ans: Result of test execution can be views in log window in Selenium IDE.

16. Where do I see the description of commands used in Selenium IDE?

Ans: Commands of description can be seen in Reference section.

17. Can I build test suite using Selenium IDE?

Ans: Yes, you can first record individual test cases and then group all of them in a test suite. Entire test suite could be executed instead of executing individual tests.

18. What verification points are available with Selenium?

Ans: There are largely three type of verification points available with selenium :

  • Check for page title
  • Check for certain text
  • Check for certain element (textbox, drop down, table etc)

19. I see two types of check with Selenium – verification and assertion, what’s the difference between two?

Ans: A verification checklets test execution continue even inthe wake of failure with check, while assertion stops the test execution. Consider an example of checking text on page, you may like to use verification point and lettest execution continue even if text is not present. But for a login page, you would like to add assertion for presence of textbox login as it does not make sense continuing with test execution if login text box is not present.

20. There is id, name, XPath, CSS locator, which one should I use?

Ans: If there are constant name/id available than they should be used instead of XPath and CSS locators. If not then CSS locators should be given preference as their evaluation is faster than XPath in most modern browsers.

21. I want to generate random numbers, dates as my test data, how do I do this in Selenium IDE?

Ans: This can be achieved by executing javascript in Selenium. Javascript can be executed using the following syntax 

Type – css=input#s– javascript{Math.random()}

22. Selenium testing – any way to speed up the selenium server load time?

Ans: It’s nice to have a new copy of a Firefox process each time, but a bit overkill to double the startup time by regenerating the Firefox profile. If you open a bug report on https://jira.openqa.org and email me at atrick@browsermob.com I’ll be happy to make sure we get a solution in place.

PS :

I’ve solved this problem as a one-off for myself. We use the same Firefox profile and just nuke out the cache and cookies DB. But I really should just patch that change back to the Selenium source.

It’s simply a matter of moving the code below outside of your test setup and into the fixture setup and keeping a global of the selenium instance (code assumes NUnit.)


public void FixtureSetup()
selenium = New DefaultSelenium(“localhost”, 4444, “*firefox”, “https://1 ocalhost/”);
Your test setup should then look something like this:
public void SetUpTest()

23. Selenium: Unable to connect to the remote server?

Ans: Make sure you have Selenium RC running. I use a simple batch file called Selenium.bat that looks like this:
Java -jar c:seleniumselenium-server.jar -multiwindow (-multiwindow prevents framekiller code from breaking your test)

24. How to set a global Base URL for every test case of one test suite in Selenium IDE?

Ans: If you have a lot of test cases in a single suite, it’s a pain to change the Base URL for each. Instead, create a separate case for each Base URL you need to switch between. For example, I have store https: //testing. site. com/asmyEnvironment saved as test case SetEnvTesting. I create another case for my production site, SetEnvProduction.

Then, insert the ${myEnvironment} at the beginning of each relative URL in your test cases. For example, open ${myEnvironment }/login . aspx. (This might be a pain if you’ve got a lot of tests already. I suggest just adding it from now on.) Then, simply put the set-environment test case at the beginning of your test suite. To switch your entire suite to another Base URL, simply put a different set-environment case at the start. Another nice thing is that you can switch environments in the middle of the suite by putting a different set-environment case in the middle.

Edit: Example of using a SetEnvironment test case.

SetEnvironment test case

Subscribe to our youtube channel to get new updates..!

How the Current environment variable is used. You can do this for every case in the suite. Additionally, you can make every separate test suite use this same SetEnvironment case, so they all switch together.

That the Base Url becomes irrelevant. You’re overriding it, essentially. I hope that’s helpful!

The test case HTML file is responsible for setting the base URL. From the Selenium IDE, you can override the base URL for a test case. A test suite, on the other hand, is only a bag for your test cases.

Remove the base URL setting from each of the test cases files referenced from your test suite. Then set the base URL by hand for the test suite and run the suite.

If it is missing, then the base URL overrides it automatically.

Found it exceedingly frustrating that couldn’t just have a blank Base URL and have it use whatever page I already had open as the start of the test. What is the point of being able to record relative URLs when it forces you to hardcode a base URL that is prefixed to every relative already had open as the start of the test? What is the point of being able to record relative URLs when it forces you to hardcode a base URL that is prefixed to every relative URL (thus turning them into absolute URLs)??

Extending on the other answers and from this Q.: In Selenium IDE, how to get the value of the base URL

You can store the current domain in a variable and then use that instead of a hardcoded one. This lets you login to the server you want to run the tests on, hit play

SetEnvironment test

And keep using the https://${host } / syntax for every truly relative URL you need in your script.


--------   Related Article: Running Test Cases - SELENIUM   --------


25. No connection could be made because the target machine actively refused it(selenium)?

Ans: The target machine actively refused it” means the server could be reached and responded within the timeout, but the specified port wasn’t open. This can have several reasons, e.g. a local firewall blocking the connection. Are you sure the server is listening on the right IP/port?

26. How to check URL for 404 using selenium webdriver?

Try this:

List alllmages
= driver.findElements(By.tagName(“img”));
for (WebElement image : alllmages) {
boolean loaded
= ((JavaScriptExecutor) driver).executeScript(
“return arguments[0].complete”, image);
if (!loaded) {
// Your error handling here.
You could use the getEval command to verify the value returned from the following JavaScript for each image on the page.
public void checkForBrokenImages() {
int imageCount
= selenium.getXpathCount(“//img”).intValue();
for (int i = 0; i < imageCount; i++) {
String currentImage
= “this.browserbot.getUserWindow().document.images[” + i
+ “i”;
assertEquals(selenium.getEval(“(!” + currentImage
+ “.complete) ? false : !(typeof ” + currentImage
+ “.naturalWidth != rundefined” && ” + currentImage
+ “.naturalWidth == 0);”), “true”, “Broken image:
” + selenium.getEval(currentImage + “.src”));


-------   Related Article: How To Setup And Configure Selenium Webdriver With Eclipse   -------


27. How to check if an element is visible with webdriver?

Ans: Try this: List alllmages

for (WebElement image : alllmages) {
boolean loaded
= ((JavaScriptExecutor) driver).executeScript(
“return arguments[0].complete”, image);
if (!loaded) {
// Your error handling here.
You could use the getEval command to verify the value returned from the following JavaScript for each image on the page.
public void checkForBrokenImages() {
int imageCount
= selenium.getXpathCount(“//img”).intValue();
for (int i = 0; i < imageCount; i++) {
String currentImage
= “this.browserbot.getUserWindow().document.images[” + i + “i”;
assertEquals(selenium.getEval(“(!” + currentImage
+ “.complete) ? false : !(typeof ” + currentImage
+ “.naturalWidth != rundefined” && ” + currentImage
+ “.naturalWidth == 0);”), “true”, “Broken image:
” + selenium.getEval(currentImage + “.src”));

Updated: Added tested TestNG/Java example.

28. How to check if an element is visible with webdrive?

Ans: Element instance of Render web element should work.
Even though I’m somewhat late answering the Q.: you can now use Web element.is displayed () to check if an element is visible.

Checkout Selenium Sample Resumes

Selenium Interview Questions For Experienced

Here are Advanced Selenium Interview Questions for Experienced

29. Webdriver and proxy server for?

Ans: Look at the documentation page.

Tweaking an existing Firefox profile

You need to change “network.proxy.http” & “network.proxy.http_port” profile settings.
FirefoxProfile profile = new FirefoxProfile();
profile.addAdditionalPreference(“network.proxy.http”, “localhost”); profile.addAdditionalPreference(“network.proxy.http_port”, “31 28”);
WebDriver driver = new FirefoxDriver(profile);
Value for network . proxy . http_port should be integer (no quotes should be used) and network. proxy. type should be set as 1 (ProxyType . MANUAL, Manual proxy settings)
FirefoxProfile profile = new FirefoxProfile();
Webdriver driver = new firefox driver (profile);
The WebDriver API has been changed. The current snippet for setting the proxy is
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“network.proxy.http”, “localhost”);
profile.setPreference(“network.proxy.http_port”, “3128”);
WebDriver driver = new FirefoxDriver(profile);
For PAC based urls
Proxy proxy = new Proxy();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
return new FirefoxDriver(capabilities);
Just had fun with this issue for a couple of days and it was hard for me to find an for HTTPS, so here’s my take, for Java:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“network.proxy.type”, 1);
profile.setPreference(“network.proxy.http”, “proxy.domain.exa mple.com”); profile.setPreference(“network.proxy.http_port”, 8080);
profile.setPreference(“network.proxy.ssl”, “proxy.domain.exam ple.com”); profile.setPreference(“network.proxy.sslport”, 8080); driver = new FirefoxDriver(profile);
Gotchas here: enter just the domain and not http: //proxy. domain . example. com, the property name is . ssl and not . https

30. Best way to take screenshots of tests in Selenium 2?

Ans: To do screenshots in Selenium 2 you need to do:

driver = new FireFoxDriver(); // Should work in other Browser Drivers driver.Navigate().GoToUrl(“https://www.theautomatedtester.co.uk “);
Screenshot ss = ((ITakesScreenshot) driver).GetScreenshot();
//Use it as you want now string screenshot = ss.AsBase64EncodedString; byte[] screenshotAsByteArray = ss.AsByteArray; ss.SaveAsFile(“filename”, ImageFormat.Png); //use any of the built in image formating ss.ToString();//same as string screenshot =
Code should work as I quickly tested it in IronPython Repl. See the IronPython code below import clr
from OpenQA.Selenium import *
from OpenQA.Selenium.Firefox import *
driver = FirefoxDriver()
driver.Navigate().GoToUrl(“https://www.theautomatedtester.co.uk “) s
= driver.GetScreenshot()
S = AsBaseEncodedString
# HUGE string appears in the REPL
I WebDriver driver = new InternetExplorerDriver(); driver.Navigate().GoToUrl(“https://www.google.com”);
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile(“ss.png”, System.Drawing.Imaging.ImageFormat.Pn );
by user800612 I don’t know if it matters, but I ended up having to cast the driver when i was writing in c#. something like:
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();

31. Take a screenshot with Selenium Webdriver?

Ans: The following example is in Java :

WebDriver driver = new FirefoxDriver();
File scrFile
= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileLJtils.copyFile(scrFile, new File(“c: mpscreenshot.png” ));
in Python:  #!/usr/bin/env python
from selenium import webdriver
browser = webdriver.Firefox()
browser.get(‘https://www.google.com/’) browser.save_screenshot(‘screenie.png’)
by In ruby:
require ‘rubygems’
require ‘selenium-webdriver’
driver = Selenium::WebDriver.for :ie
driver.get “https://rAgw.google.com”
more file types and options are available and you can see them in takes_screenshot.rb
WebDriver augmentedDriver = new Augmenter().augment(driver); ((TakesScreenshot)augmentedDriver).getScreenshotAs(…); //wor ks this way
In PHP (using PHPUnit_Selenium extension version 1.2.7):
Skip code block
class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase
public function screenshot($filepath) {
$filedata = $this->currentScreenshot();
file_put_contents($filepath, $filedata);
public function testSomething() {

32. Cucumber and Capybara, clicking a non-link or button element?

Ans: You can click on an element via Capybara : 

Element . click.
I add the following for this in my web_steps rb to click on divs.
When /A(?:II )click within “([“”]*)”$/ do ‘selector’ find(selector).click end
There is also Element . t rigger ( ‘ mouseover ‘ ) which appears to enable hover albeit not working with Selenium.
It is also very likely you will need to decorate your feature/scenario with Capybara’s provided @javascript

33. What’s the relationship between selenium RC and webdriver?

Ans: You should probably start your research here (though you may have already gone over  Selenium Org

I’ll assume you’re contrasting Selenium-RC to WebDriver, Selenium-IDE really isn’t in the same ballpark.

Selenium uses JavaScript to automate web pages. This lets it interact very tightly with web content, and was one of the first automation tools to support Ajax and other heavily dynamic pages.

However  this also means :

Selenium runs inside the JavaScript sandbox. This means you need to run the Selenium-RC server to get around the same-origin policy, which can sometimes cause issues with browser setup.

WebDriver, on the other hand, uses native automation from each language. While this means it takes longer to support new browsers/languages, it does offer a much closer ‘feel’ to the browser. If you’re happy with WebDriver, stick with it, it’s the future.

There are limitations and bugs right now, but if they’re not stopping you, go for it.

Selenium Benefits over WebDriver:

  1. Supports many browsers and many languages, WebDriver needs native implementations for each new language/browser combo.
  2. Very mature and complete API
  3. Currently (Sept 2mo) supports JavaScript alerts and confirms better

Benefits of WebDriver Compared to Selenium

  1. Native automation faster and a little less prone to error and browser configuration
  2. Does not require Selenium-RC Server to be running
  3. Access to headless HTMLUnit can allow tests to run very fast Great API

Selenium WebDriver is the successor of Selenium Remote Control which has been officially deprecated. The Selenium Server (used by both WebDriver and Remote Control) now also includes built-in grid capabilities. So it’s settled :-)

34.selenium.wait_for_condition equivalent in Python bindings for WebDriver?

Ans: Currently, it isn’t possible to use wait for condition Currently it isn’t possible to use wait_for_condition with WebDriver. The python selenium code does provide the DrivenSelenium class for accessing the old selenium methods, but it can’t do wait_for_condition. The selenium wild has some info on that.

Your best bet is to use the WebDriverWait class. This is a helper class that periodically executes a function waiting for it to return True. My general usage is
Skip code block

driver = webdriver.Firefox()
add = driver.find_element_by id(“ajax_button”)
add. click() source = driver.page_source
def compare_source(driver):
return source != driver.page_source
except WebDriverException:
WebDriverWait(driver, 5).until(compare_source)
# and now do some assertions

This solution is by no means ideal. The try/except is necessary for situations where the page request/response cycle is delayed waiting for some ajax activity to complete.
If compare_source get’s called in the midst of the request/response cycle it’ll throw a WebDriverException. The test coverage for WebDriverWait is also helpful to look at.


-------   Related Page: How To Install Debugbar Tool - SELENIUM   ------


35. Is there an HtmlUnitDriver for .NET?

Ans: To use HtmlUnit you need to use the RemoteWebDriver and pass in the desired capabilities for it.

IWebDriver driver

= new RemoteWebDriver(DesiredCapabilities.HtmlUnit())

and away you go. If you want the Firefox implementation to run use

IWebDriver driver

= new RemoteWebDriver(DesiredCapabilities.HtmlUnitWithJavaScript())

36.How to hide Firefox window (Firefox WebDriver)?

Ans: Found the solution for those who are using windows Machine for running the Tests using any method. Well, implementation is not in java but you can do it very easily.
Use AutoIt tool.
It has all the capability to handle windows. It is a free Tool.

1. Install Auto it: https://www.antoitscriptecom/site/autoit/downloads/

2. Open the Editor and write below code for Hiding any window.

AutoItSetOption(“WinTitleMatchMbde”, 2)
WinSetState(“Title Of Your Window”, “”, @SHOW)
WinTitleMatchMode has different options which can be used to match Windows title.
1 = Match the title from the start (default)
2 = Match any substring in the title
3 = Exact title match
4 = Advanced mode, see Window Titles & Text (Advanced)
So what I am doing is: I have created exe of a small program and passing parameter as command line argument as below.
Runtime.getRuntime().exec(“C:/Diiinnovation/HideNSeek.exe 0 ”” + “Mozilla Firefox” + “””);
in HideNSeek . exe – I have below Autolt Code: AutoItSetOption(“WinTitleMatchMode, 1)
if $CmdLine[0] > 0 Then
if $CmdLine[1] == 0 Then
WinSetState($CmdLine[2], “”, @SW_HIDE)
Elself $CmdLine[1] == 1 Then
WinSetState($CmdLine[2], “”, (dSW_SHOW)
$cmdL ine [ ] is an array which will have all command line parameters.
$CmdLine[0] = number of Parameter
$CmdLine[1] = 1st Parameter after Exe Name

If there is any space in the Window Title then you have to use double quotes to pass it as a command line parameter like above.

Below Line of code will execute Auk& exe and if I pass ‘o’ in 1st parameter then it will hide the window and if I will pass ‘1’ then it will unhide windows matching the title.
Runtime.getRuntime().exec(“C:/Diiinnovation/HideNSeek.exe 0 ”” + “Mozilla Firefox” + “””);

37. WebDriver (Selenium 2) API documentation?

Ans: There are javadocs here, rubydocs here, python docs here, .NET docs here, and documentation for WebDriverJS (JavaScript) here.
The official Python API docs are here: https://selenium.googlecode.com/svn/trunk/docs/api/py/index.h tml
They’re no longer missing the classes that James mentioned in his previous comment.

There’s also an unofficial set of python docs here:

which is more of a walkthrough.

The Javascript Bindings are well commented, but it seems that nobody bothered to generate some HTML documentation from them. Anyway, browsing the code and reading the comments is helpful:
https://code.google.com/p/selenium/source/browse/#svn%2Ft runk%2Fjavascript%2Fwebdriver

Most helpful for me was webdriver.js.

True, BASIC HTIT authentication is not currently supported but I got it working now for FF and for Chrome. The code I wrote in the Q.s works for those drivers. I j tried using FF3.6 as Firefox default browser (installed in Firefi folder) instead of FF4 (not supported yet). For IE, i may try to disable the authentication through Windows Registry.

got it to work with Firefox webdriver by the following:

profile.SetPreference(“network.automatic-ntlm-auth.trusted-uris”, “google.com”);
driver = new FirefoxDriver(profile);

38. Selenium 1 to selenium 2 migration ?

Ans: Going through the transition myself. If you had Selenium 1 experience, Selenium 2 feels quite different actually. Here is my Selenium 2 pros/cons vs. Selenium 1 I see so far (I use Python so some of them are Python specific):


  • Much faster
  • No need to run a separate server

Gone are wait_for_page_to_loada wait_for_element_presenta etc. All element interactions, clicks, etc. are blocking now, which is good. The only problem is with asynchronously loaded content (Ajax) though, see Con bellow.


Loading/waiting for asynchronous content which used to be “free” with wait_for_page_to_load() requires coding now. These are the solutions I found so far:
use PageFactory/AjaxElementLocatorFactory like explained here, unfortunately, I couldn’t find the equivalent for Python.
use webdriver.implicitly_wait(N), this seems to be doing the trick with Python but using that seems to cause my script to miss changing elements which it used to detect before.
don’t do sleep(T), loop until element appears, etc, that defeats the Duruose of the whole thing (and makes Defeats the purpose of the whole thing (and makes wait_for_page_to_load look beautiful)…

  • The whole thing still feels a bit raw. Different drivers and bindings seem to miss different functionality. Not to say you can’t use it but be ready to find ‘alternate solutions’ for certain problems.
  • The documentation is a bit dubious (related to the prey. point I guess). Especially for Python. Be ready to read code and experiment a lot (which luckily is easy with Python). Most of the ‘tutorials’ you’ll find on the web (again, esp. Python, Java seems to be much better covered) are just to get you started with the plainest of web applications.
  • No PHP bindings, not a big one I prefer Python but our original suite was PHP so I noticed.
  • SeleniumlDE seems to be useless with Selenium 2

Other differences :

The page elements you are accessing have to be ‘visible’ on the page at the moment when you ask selenium to find them. For example if you have a menu (containing a list of links) which opens when you hover your mouse over, you have to make sure it is open/visible before you click on a link inside (which wasn’t the case in Selenium 1). This has it’s uses since you’d be testing what a user would see on the page but requires the extra code. I found two solutions:

run a Javascript which would open your menu, in my case

driver.execute script(“document.getElementById(‘d ashboard menu navigation’).show()”)thenclickthe menu item
driver.find element_by_link text(‘Orders’).click( )
use the Mouse / Keyboard classes to simulate actual interaction, this seems to be broken in the Python bindings though (see Cons above):
Example (which throws ‘ web E lement ‘ object has no attribute ‘mouse move to’ today): element=driver.find_element_by_id(‘mn_dashboard’)

The Cons list seems longer but that is mostly if you are coming from Selenium 1. I do prefer the lightness and speed of Selenium 2 and despite the early code (using 2.ob4 at the time of writing) the whole thing is quite usable.

Moving from Selenium 1 to Selenium 2 is as simple moving from

Selenium selenium
= new DefaultSelenium(“localhost”, 4444, “*firefox”, “https://www.examp le.com”);
selenium.open(“/”); to
Webdriver driver = new FirefoxDriver();
Selenium selenium
= new WebDriverBackedSelenium(driver, “https://www.example.com”);

Since Selenium 2 is more tightly bound to the browser you will see a huge difference. I have seen tests running at least 2x faster but in some cases, I have seen it running zix faster.
All the same best practices that you learned during Selenium will be translated across

Checkout Selenium Tutorial

39. Does anyone know of any decent alternatives to SauceLabs OnDemand Selenium service?

Ans: It Lists a couple of alternatives
An alternative would be TestingBot. They provide the same Selenium service at a slightly cheaper price.

40. Where is WebDriver’s Python API Documentation?

Ans: The official documentation is available on the Selenium Google Page. The ReadTheDocs version is not official and not maintained by the Selenium project so may or may not be in date
The API docs for the Webdriver Python bindings are now at https://readthedocs.org/docs/selenium-python/en/latest/ (Unofficial)

Just thought I share this in case it can come in handy. Skip code block
add cookie
Adds a cookie to your current session.


cookie_dict: A dictionary object, with the desired
cookie name as the key, and
the value being the desired contents.


driver.add_cookie(cfoo’: ‘bar’,})
Goes one step backward in the browser history.
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = { }
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the
name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Closes the current window.
Usage: driver. close()
command_ executor
A connection with the Remote WebDriver server.
Communicates with the server using the WebDriver wire protocol: https://code.google.com/p/selenium/wiki/lsonWireProtocol
Creates a web element with the specified element_id.
unicode(string [, encoding[, errors]]) -> object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be ‘strict’, ‘replace’ or ‘ignore’ and defaults to ‘strict’.
unicode(string [, encoding[, errors]]) -> object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be ‘strict’, ‘replace’ or ‘ignore’ and defaults to ‘strict’.
Delete all cookies in the scope of the session.
Usage: driver. delete_all_cookies()
delete cookie
Deletes a single cookie with the given name.
driver.delete cookie (“my cookie”)
Handles errors returned by the WebDriver server.
sends a command to be executed by a command. Commandexecutor.


driver_command: The name of the command to execute as a string.
params: A dictionary of named parameters to send with the command.


The command’s JSON response loaded into a dictionary object.
params: A dictionary of named parameters to send with the command. Returns:
The command’s JSON response loaded into a dictionary object.
execute async script
synchronously Executes JavaScript in the current window/frame.
script: The JavaScript to execute.
Any applicable arguments for your JavaScript. Usage:
driver.execute async script(“document.title’)
execute script
Synchronously Executes JavaScript in the current window/frame.
Args: script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript. Usage:
driver.execute script(“document.title’)
‘Private method used by the find_element_by_* methods. Usage:
Use the corresponding find_element_by_* instead of this.
Finds an element by class name. Args: name: The class name of the element to find.
Finds an element by ces selector.
Args: css_selector:
The css selector to use when finding elements.
driver.find_element_by_css_selector (“*foo”)
Finds an element by id.
id_: The id of the element to be found.
driver.find_element_by_ids ‘foo’)
Finds an element by link text. Angs: link_text: The text of the element to be found.
driver.find_element_by_link_text(“Sign In”)
Finds an element by name. Angs:
name: The name of the element to find.
Finds an element by a partial match of its link text.
link_text: The text of the element to partially match on.
Finds an element by tag name.
name: The tag name of the element to find.
Finds an element by xpath.
Args: xpath:
The xpath locator of the element to find.
driver.find_element_by_xpath (“//divistd[1]”)
“Private method used by the find_elements_by_* methods.
Use the corresponding find_elements_by_* instead of this.
Finds elements by class name. Args: name: The class name of the elements to find.
Finds elements by cos selector.
css_selector: The css selector to use when finding
driver.find_element_by_css_selector (“*foo”)
Finds multiple elements by id. Angs: id_: The id of the elements to be found.
Finds elements by link text.
Args: link_text: The text of the elements to be found.
driver.find_elements_by_link_text(“Sign In”)
Finds elements by name. Args: name: The name of the elements to find.
Finds elements by a partial match of their link text.
link_text: The text of the element to partial match on.
Finds elements by tag name. Args: name: The tag name the use when finding elements.
Finds multiple elements by xpath. Angs: xpath: The xpath locator of the elements to be found.
driver.find_elements_by_xpath (“//divscontains (@class, ‘foo’)]”)
Goes one step forward in the browser history.
driver. forward()
Loads a web page in the current browser session.
Get a single cookie by name. Returns the cookie if found, None if not.
driver.get_cookie (“my cookie”)
Returns a set of dictionaries, corresponding to cookies visible in the current session. Usage:
Returns the handle of the current window. Usage: driver.get_current_window_handle() Note: this method has been deprecated. Please use current_window_handle
Gets the source of the current page. Usage: driver.get_page_source() Note: This call has been deprecated. Please use page_source
Property get_screenshot as base64
Gets the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML.
driver.get_screenshot as base64
get_screenshot as file
Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename.
filename: The full path you wish to save your screenshot to.
driver.get_screenshot as file(‘s Screenshots/foo.png”)
Returns the handles of all windows within the current session. Usage: driver.get_window_handles() Note: this method has been deprecated. Please use window_handles
implicitly wait
sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. Args: time_to_wait: Amount of time to wait Usage:
driver.implicitly wait(30)
unicode(string I, encodings, errors]]) -> object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be ‘strict’, ‘replace’ or “ignore” and defaults to
unicode(string I, encodings, errors]]) -> object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be ‘strict’, ‘replace’ or “ignore” and defaults to
quit Quits the driver and closes every associated window. Usage:
driver. Quit()
Refreshes the current page. Usage:
Unicode (string [, encoding [ , errors]]) -> object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be ‘strict’, ‘replace’ or ‘ignore” and defaults to
Set the amount of time that the script should wait before throwing an error. Angs: time_to_wait: The amount of time to wait Usage:
driver.set_script timeout (30)
Called before starting a new session. This method may be overridden
to define custom startup behavior.
Creates a new session with the desired capabilities.
browser name: The name of the browser to request.
version: which browser version to request.
platform: which platform to request the browser on.
javascript enabled: whether the new session should support JavaScript.
browser profile: A browser profile directory as a Base64encoded
zip file. Only used if Firefox is requested.
stop client
Called after executing a quit command. This method may be overridden
to define custom shutdown behavior.
Returns the element with focus, or BODY if nothing has focus. Usage:
Switches focus to an alert on the page. Usage:
switch_to_default content
Switch focus to the default frame.
driver.switch_to_default content()
Switches focus to the specified frame, by index or name.
index_or_name: The name of the window to switch to, or
an integer representing the index to switch to.
driver.switch_to_frame(‘frame name”)
Switches focus to the specified window. Args: window_name: The name of the window to switch to. Usage:
unicode(string I, encodings, errors]]) -> object
Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be “strict’, ‘replace’ or “ignore” and defaults to
list() -> new empty list list(iterable) -> new list initialized from iterable’s items
Tags: webdriver (Next Q), python (Next Q)


------   Related Page: Locators & How To Install Firebug - SELENIUM   ------


41. How to deal with file uploading intest automation using selenium or webdriver ?

Ans: Webdriver can handle this quite easily in IE and Firefox. Its a simple case of finding the element and typing into it.

driver = webdriver. Firefox()
element = driver.find_element_by_id(“fileUpload”)
element.send_keys(“my file.txt”)

The above example is in Python but you get the idea

42. WebDriver: get HTTP Response Code?

Ans: In a word, no, it’s not possible using the Selenium WebDriver API. This has been discussed adnauseum in the issue tracker for the project, and the feature will not be added to the API.

43. New WebDriver instance per test method?

Ans: Found that reusing browser instances between test methods has been a huge time saver when using real browsers, e.g. Firefox. When running tests with HtmlunitDriver, there is very little benefit.

Regarding the danger of indeterministic tests, it’s a trade-off between totally deterministic tests and your time. Integration tests often involve trade-offs like these. If you want totally deterministic integration tests you should also be worrying about clearing the database/server state in between test runs.

One thing that you definitely should do if you are going to reuse browser instances isto clear/store the cookies between runs. driver-manage().deleteallcookies();
I do that in a teardown() method. Also if your application stores any data on the client side you’d need to clear that (maybe via JavascriptExecutor). To your application which is under test, it should look like a completely unrelated request after doing this, which really minimizes the risk of indeterministic behaviour.

44. Selenium: FirefoxProfile exception Can’t load the profile?

Ans: Update: Selenium team fixed in latest version. For almost all environments the fix is:

pip install-Uselenium

Unclear at which version it was fixed (apparently r13122), but certainly by 2.26.0 (current at time of update) it is fixed.

This error means that _wait_until_connectable istiming out, because for some reason, the code cannot connect to the webdriver extension that has been loaded into the firefox.

I have just reported an error to selenium where I am getting this error because I’m trying to use a proxy and only 2 of the 4 configured changes in the profile have been accepted by firefox, so the proxy isn’t configured to talk to the extension. Not sure why this is happening…

https://code.google.com/p/selenium/issues/detail?id=2061 by user.1380597

I had the same issue after upgrading Ubuntu to 12.04. The issue was on the package side and has been fixed in the latest version of the library. Just update the selenium library. For almost all Python environments this is:

pip install -U selenium

faced the same problem with FF 32.0 and Selenium selenium2.42.1-py?.7.egg. Tried to update selenium, but it is already the latest version. The solution was to downgrade Firefox to version 30. Here is the process:

#Download version 30 for Linux (This is the 64 bit)
tar -xjvf firefox-39.e. tar.bz2
#Remove sudo rm sudo mv #Create
sudo ln
The old version -rf /opt/firefoxfirefox /opt/firefox36.9 a permanent link
-sf/opt/firefox39.8/firefox /usr/bin/firefox
This solved all the problems, and this combination works better

45. How to stop selenium from creating temporary temporary firefox profiles using web driver?

Ans: You can control how the Firefox driver chooses the profile. Set the webdriver. firefox. profile property to the name of the profile you want to use. Most folks think this is abad idea, because you’ll inherit all the cookies, cache contents, etc. of the previous uses of the profile, but it’s allowed if you really want to do it.

For example : System.setProperty(“webdriver.+irefox.profile”, “MyseleniumProfile”); WebDriver driver = new FirefoxDriver(…);

UPDATE – From Ranhiru

How I handled it for Java FirefoxProfile profile = new FirefoxProfile(new File(“D:selenium Profile”)); WebDriver driver = new FirefoxDriver(profile);
Then I changed settings in Firefox to clear all cookies and cache when exiting. Look here on how to do it.


-------    Related Article: Selenium WebDriver Commands List    ------- 


46. Selenium WebDriver how to close browser popup ?


( ( javascrip executor ) _driver )
.executescript (“ window. Onbeforeunload = function (e)
{ }; “ ) ;
Solved the issue for me
I Alert alert = driver. SwitchTo(). Alert();
alert. Accept(); //for two buttons, choose the affirmative one // or
alert. Dismiss(); // to cancel the affirmative decision, i.e.,
pop up will be dismissed and no action will take place
You can interact with alerts and the like using the Alert API. Switching to the alert and confirm it would look like this (in Java):
Alert alert = driver.switchTo().
alert(); alert. accept();
This is also explained in the Selenium FAQ.
def close_all_popups (driver):

47. Selenium WebDriver to select combo-box item?


This is how to do it:
@ When(“I select $elementId value $value”)
public void selectComboValue(final String elementId, final String valu e)
final Select selectBox
= new Select(web.findElement(By.id(elementId)));
selectBox. selectByValue(value);
  The Support package in Selenium contains all you need:
using OpenQA. Selenium. Support. UI:
SelectElement select = new SelectElement(driver.findElement( By.id( el
ementId ) ));
select. SelectByText(“Option3”);
select. Submit (); You can import it through NuGet as a separate package:
Tags: webdriver (Next Q)

48. Selenium c# Webdriver: WaitUntilElementis Present

Ans: Alternatively you can use implicit wait:

driver.Manage(). Timeouts(). Implicitlywait(Timespan. FromSeconds(10));

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is o. Once set, the implicit wait is set for the life of the WebDriver object instance.

Using the solution provided by Mike Kwan may have an impact in overall testing performance, since the implicit wait will be used in all FindElement calls. Many times you’ll want the FindElement to fail right away when an elementis not present (you’retesting for a malformed page, missing elements, etc.). With the implicit wait these operations would wait for the whole timeout to expire before throwing the exception.

I’ve written a little extension method to to IWebDriver that adds a timeout (in seconds) parameter to the FindElement() method. It’s quite self-explanatory: Skip code block
public static class WebDriverExtensions

This is how to do it:
@ When(“I select $elementId value $value”)
public void selectComboValue(final String elementId, final String valu e)
final Select selectBox
= new Select(web.findElement(By.id(elementId)));
selectBox. selectByValue(value);
  The Support package in Selenium contains all you need:
using OpenQA. Selenium. Support. UI:
SelectElement select = new SelectElement(driver.findElement( By.id( el
ementId ) ));
select. SelectByText(“Option3”);
select. Submit (); You can import it through NuGet as a separate package:
Tags: webdriver (Next Q)

You can also use

Expected Conditions. ElementExists

So you will search for an element availability like that
new WebDriverWait(driver, TimeSpan. FromSeconds(timeOut)). Until(Expecte dConditions. ElementExists ((By. Id(login))));


Here’s a variation of GLoudenvier’s solution that also works for getting multiple elements: Skip code block

public static class WebDriverExtensions

public static IWebElement FindElement(this IWebDriver driver, By by, int timeout InSeconds) { if (timeoutInSeconds » 9) { var wait
= new WebDriverWait(driver, Timespan. From Seconds (timeout1nSeconds));
return wait. Until(drv => drv. FindElement(by));
return driver. FindElement (by);
public static ReadOnlyCollection«IWebElement». FindElements(this IWebD river driver, By by, int timeoutInSeconds)
if (timeoutInSeconds  > 0 )
var wait
= new WebDriverWait(driver, Timespan. FromSeconds (timeout1nSeconds));
return wait. Until(dry => (dry. FindElements (by). Count > 0) 2 drv. FindElements (by) : null);
return driver. FindElements (by);
Confused anyomous function with predicate. Heres a little
helper method:
WebDriverwait wait;
private void waitForby Ids string id)
{ if (wait == null) wait = new WebDriverWait(driver, new TimeSpan(0,0,5)); //wait. Until(driver); wait. Until(d => d. FindElement(By. Idsid))); }


------   Related Page: Sample Programs In Remote Control For Selenium   ------


49. What is the difference between Selenium IDE, Server, RC, 2.o, and WebDriver?

Ans: You’re almost right.

Selenium IDE is a Firefox plugin used for rapid prototyping oftest cases in Selenese/HTML, which canalso export test cases in a variety of programming languages.
Selenium Server is a standalone java program which allows you to run test cases written in a variety of programming languages with a variety of web browsers, and which can additionally run HTML test suites in a range of different browsers, plus extra options like reporting. (My point is that the –htmlsuite option of selenium-serverjar is not its primary function, and will soon be split out into a separate program.)

Selenium Remote Control is an API for programming tests in a variety of languages in Selenium 1 and Selenium 2, and also the name of the Selenium 1 server that runs the API.
WebDriver is an API for programming tests in a variety of  languages in Selenium 2, which can run with or without a Server. • Selenium 2 is the latest version of the Selenium project, and includes the IDE, Server and both the Selenium RC and WebDriver APIs.

In addition:
  • Selenium Grid is a server that distributes tests across a set of Selenium Servers. In Selenium 1 it is a separate server, in Selenium 2 it is integrated into the Selenium Server.

50. Selenium WebDriver and DropDown Boxes

Ans: You could try this:

IWebElement dropDownListBox = driver. FindElement(By. Ids”selection”));
SelectElement clickThis = new SelectElement(dropDownListBox);
clickThis. SelectByText(“Germany”);

Try the following:

import org.openqa.selenium.support.ui.Select;
Select droplist = new Select(driver.findElement(By. Ids”selection”)));

51. Get HTML SOURCE OF WebElement in selenium web driver (python)

Ans: There is not really a straight-forward way of getting the html source code of a webelement. You will have to use JS. I am not too sure about python bindings but you can easily do like this in Java. I am sure there must be something similar to JavaScriptExecutor class in Python.

WebElement element = driver.findElement(By.id(“foo”));
String contents = (String)
((Javascript=xecutor) driver).
executeScript(“return arguments[9].innerHTML;”, element);

If you are interested to learn Selenium and build a career in Automation Testing? Then check out our Selenium Certification Training Course at your near Cities

Selenium Training New York, Selenium Training Dallas

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Selenium and help you to achieve your dream job.