Mindmajix

Selenium Interview Questions

Selenium Interview Questions

Q. What is Selenium?

Selenium is one of the most powerful open source automation tool for web application testing (even we can say acceptance testing for web application) which lets you automate operations like — type, click, 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.


Q. Who developed Selenium Tool and Why?

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).


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

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.


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

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.


Q. Which Selenium Tool should I use?

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


Q. What is Selenium IDE?

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.


Q. Which language is used in Selenium IDE?

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


Q. What is Selenium 1.0?

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.


Q. What is Selenium 2.0?

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.


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

There are mainly 4 locators used with Selenium

– html id

– html name

– XPath locator and

– Css locators


Q. What is Selenium Grid?

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.


Q. What is an Accessor in Selenium?

Accessor is one of the type of Selenese.

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

Ex

  • storeTitle — Stores the title of a window in a variable
  • 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

Ex: storeTextPresent — Evaluates whether the text is present in the current window. If the text is present stores true in the variable else stores false

Ex: 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.


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

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.


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

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


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

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


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

Commands of description can be seen in Reference section.


Q. Can I build test suite using Selenium IDE?

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.


Q. What verification points are available with Selenium?

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)


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

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.


Q. I don’t see checkpoints added to my tests while using Selenium IDE, how do I get them added to my tests?

You need to use context menu to add checkpoints to your Selenium IDE tests.


Q. How do I edit tests in Selenium IDE2

There are two ways to edit tests in Selenium IDE; one is the table view while other looking into the source code of recorded commands.


Q. What is syntax of command used in Selenium?

There are three entities associated with a command—

  • Name of Command
  • Element Locator (also known as Target)
  • Value (required when using echo, wait etc)

Q. There are tons of Selenium command, am I going to use all of them

This entirely bils down to operations you are carrying out with Selenium. Though, you would definitely be usingfollowing Selenium Commands more often –

Open: opens a web page.

Click/click And Wait: click on an element and waits for a new page to load.

Select: Selects a value from a drop down value.

VerifyTitle/assertTitle: verifies/asserts page title.

Verify/assert ElementPresent: verifies/asserts presence of element, in the page.

Verify/assert TextPresent: verifies/asserts expected text is somewhere on the page.


Q. How do I use htmlid and name while using Selenium IDE2

Htmlid and name can be used as it is in selenium IDE.

For example Google search box has name – “q” and id – “list-b” and they can be used as target in selenium IDE.


Q. What is XPath? When would I have to use XPath in SeleniumIDE?

XPath is a way to navigate in xml document and this can be used to identify elements in a web page. You may have to use XPath when there is no name/id associated with element on page or only partial part of name/ide is constant.

Direct child is denoted with – /

Relative child is denoted with – //

Id, class, names can also be used with XPath –

  • //input[@name=’0
  • //input[@idAst-ibl
  • //input[@class=’ 1st’]

If only part of id/name/class is constant than “contains” can be used as –

  • //input[contains(@id.’lst-ib’)]

Q. What is CSS location strategy in Selenium?

CSS location strategy can be used with Selenium to locate elements, it works using cascade style sheet locationmethods in which —

Direct child is denoted with — (a space)

Relative child is denoted with – >

Id, class, names can also be used with XPath —

  • css=input[name=’q’]
  • css=input[idAst-ibl or input#1st-ib
  • css=input[class=’ 1st’] or input.lst

If only part of id/name/class is constant than “contains” can be used as —

  • css=input[id*=’ lst-ib ‘A

Element location strategy using inner text

  • css = a:contains(`log out’)

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

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.


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

This can be achieved by executing java script in Selenium. Java script can be executed using following syntax —

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


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

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 http://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.)

[TestFixtureSetUp()]

public void FixtureSetup()

{

selenium = New DefaultSelenium(“localhost”, 4444, “*firefox”, “http://1 ocalhost/”);

selenium.Start();

selenium.SetTimeout(“30000”);

selenium.Open(“/”);

}

Your test setup should then look something like this:

[Setup()]

public void SetUpTest()

{

selenium.Open(“default.aspx”);

selenium.WaitForPageToLoad(“30000”);

}


Q. Selenium: Unable to connect to the remote server

Make sure you have Selenium RC running. I use a simple batch file called Selenium.bat that looks like this:

Java -jar c:\selenium\selenium-server.jar -multiwindow (-multiwindow prevents framekiller code from breaking your test)


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

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.

Screenshot_1

  1. How the Currentenvironment 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.
  2. 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 case files referenced from your test suite. Then set the base URL by hand for the test suite and run the suite.

The line in Q. is in the head of each test case file:

<link href=”http://server-name/” rel=”selenium.base”/>

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 absoulte 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 hard coded one. This lets you login to the server you want to run the tests on, hit play and it will run the tests without all this baseURL nonsense redirecting you to the wrong server. Just use these commands at the start of the first script in your suite:

Screenshot_2

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


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

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?


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

Try this:

List<WebElement> 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.

@Test

public void checkForBrokenImages() {

selenium.open(“http://www.example.comr);

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”));

}

}


Q. How to check if an element is visible with webdriver

Try this: List<WebElement> 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.

@Test

public void checkForBrokenImages() {

selenium.open(“http://www.example.comr);

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.


Q. How to check if an element is visible with webdrive

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.


Q. Webdriver and proxy server for firefox

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”, “localho st”); 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();

proxy.setProxyType(Proxy.ProxyType.PAC);

proxy.setProxyAutoconfigUrl(“http://some-server/staging.pac”);

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


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

To do screenshots in Selenium 2 you need to do

driver = new FireFoxDriver(); // Should work in other Browser Drivers driver.Navigate().GoToUrl(“http://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 =

ss.AsBase64EncodedString;

Code should work as I quickly tested it in IronPython Repl. See the IronPython code below import clr

clr.AddReference(“WebDriver.Common.d11”)

clr.AddReference(“WebDriver.Firefox.dll”)

from OpenQA.Selenium import *

from OpenQA.Selenium.Firefox import *

driver = FirefoxDriver()

driver.Navigate().GoToUrl(“http://www.theautomatedtester.co.uk “) s

= driver.GetScreenshot()

S = AsBaseEncodedString

# HUGE string appears in the REPL

I WebDriver driver = new InternetExplorerDriver(); driver.Navigate().GoToUrl(“http://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();


Q. Take a screenshot with Selenium Webdriver

The following example is in Java:

WebDriver driver = new FirefoxDriver();

driver.get(“http://www.google.comr);

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:\\tmp\\screenshot.png” ));

in Python:  #!/usr/bin/env python

from selenium import webdriver

browser = webdriver.Firefox()

browser.get(‘http://www.google.com/’) browser.save_screenshot(‘screenie.png’)

browser.quit()

by In ruby:

require ‘rubygems’

require ‘selenium-webdriver’

driver = Selenium::WebDriver.for :ie

driver.get “https://rAgw.google.com”

driver.save_screenshot(“iscreen.png”)

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() {

$this->screenshot(‘/path/to/screenshot.png’);

}

…..

}


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

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

Tag.


Q. What’s the relationship between selenium rc and webdriver?

You should probably start your research here (though you may have already gone over this):  http://seleniumhq.org/docs/o3_webdriver.html

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

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

 Benefits of WebDriver Compared to Selenium

  • Native automation faster and a little less prone to error and browser configuration
  • Does not require Selenium-RC Server to be running
  • 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 :-)


Q. selenium.wait_for_condition equivalent in Python bindings for WebDriver

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()

driver.get(‘http://example.com’)

add = driver.find_element_by id(“ajax_button”)

add. click() source = driver.page_source

def compare_source(driver):

try:

return source != driver.page_source

except WebDriverException:

pass

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.


Q. What is the difference between Selenium’s Remote Control vs WebDriver?

WebDriver is now Selenium 2. The Selenium and WebDriver code bases are being merged. WebDriver gets over a number of issues that Selenium has and Selenium gets over a number of issues that Webdriver has.

If you have written your tests in Selenium one you don’t have to rewrite them to work with Selenium 2. We, the core developers, have written it so that you create a browser instance and inject that into Selenium and your Selenium 1 tests will work in Selenium 2. I have put an example below for you.

Skip code block

// You may use any WebDriver implementation. Firefox is used here as an example

WebDriver driver = new FirefoxDriver();

// A “base url”, used by selenium to resolve relative URLs

String baseUrl = “http://www.google.com”;

// Create the Selenium implementation

Selenium selenium

= new WebDriverBackedSelenium(driver, baseUrl);

// Perform actions with selenium selenium.open(“http://www.google.com”);

selenium.type(“name=q”, “cheese”);

selenium.click(“name=btnG”);

Selenium 2 unfortunately has not been put into Selenium 2 but it shouldn’t be too long until it has been added since we are hoping to reach beta in the next couple of months.

Skip code block

public void StaleElementHandleBylD (String elementlD){

int count = 0;

while (count < 4){

try {

WebElement yourSlipperyElement= driver.findElement(By.id(elementID));

yourSlipperyElement.click();

} catch (StaleElementReferenceException e){ e.toString();

System.out.println(“Trying to recover from a stale element :” + e.getMessage());

count = count+1;

}

count = count+4;

}

I’d recommend only using this on elements you know cause problems for WebDriver.

We get around this issue by doing something called WebdriverWrapper and WebElementWrapper.

What these wrappers do is handle the StaleElementException within and then use the locator to re-evaluate and get the new WebElement object. This way, you need to spread the code handling the exception all over your codebase and localize it to one class.

I will look into open sourcing just these couple of classes soon and add a link here if you folk are interested.


Q. Is there an HtmlUnitDriver for .NET?

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())


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

Found the solution for those who is using windows Machine for running the Tests using any method. Well, implementation is not in iava but you can do it very easily.

Use Autolt tool.

It has all the capability to handle windows. It is free Tool.

1. Install Auto it: http://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)

Else

Endlf

Endlf

$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” + “\””); I hope this will

help you. thanks!


Q. WebDriver (Selenium 2) API documentation

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: http://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:

http://readthedocs.org/docs/selenium-python/en/latest/index.html

which is more of a walkthrough.

The Javascript Bindings are well commented, but it seems that ,  nobody bothered to genereate some html documentation from them. Anyway, browsing the code and reading the comments is helpful:

http://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 supporter 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.

This page

http://code.google.com/p/selenium/issues/detai id=34  may help.

 got it to work with Firefox webdriver by the following:

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

driver = new FirefoxDriver(profile);

driver.Navigate().GoToUrl(“http://user:pwdggoogle.com-),


Q. Selenium 1 to selenium 2 migration

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):

Pros:

  • 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.

 Cons:

  • 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 an 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’)

mouse=Mouse()

mouse.move_to(element)

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.

Hope to save someone some time…

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

Selenium selenium

= new DefaultSelenium(“localhost”, 4444, “*firefox”, “http://www.examp le.com”);

selenium.open(“/”); to

Webdriver driver = new FirefoxDriver();

Selenium selenium

= new WebDriverBackedSelenium(driver, “http://www.example.com”);

selenium.open(“/”);

Since Selenium 2 is more tightly bound to the browser you will see 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 practises that you learnt during Selenium will be the translated across


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

Have a look at http://seleniumhq.org/support/

it lists a couple of alternatives

An alternative would be TestingBot. They provide the same Selenium service at a slightly cheaper price.


Q. Where is WebDriver’s Python API Documentation?

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 http://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.

Args:

cookie_dict: A dictionary object, with the desired

cookie name as the key, and

the value being the desired contents.

Usage:

driver.add_cookie(cfoo’: ‘bar’,})

back

Goes one step backward in the browser history.

Usage:

driver.back()

capabilities

dict() -> new empty dictionary

dict(mapping) -> new dictionary initialized from a mapping

object’s

(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)

close

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: http://code.google.com/p/selenium/wiki/lsonWireProtocol

create_web_element

Creates a web element with the specified element_id.

current_url

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’.

current_window_handle

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

Delete all cookies in the scope of the session.

Usage: driver. delete_all_cookies()

delete cookie

Deletes a single cookie with the given name.

Usage:

driver.delete cookie (“my cookie”)

error_handler

Handles errors returned by the WebDriver server.

execute

sends a command to be executed by a command. Commandexecutor.

Args:

driver_command: The name of the command to execute as a string.

params: A dictionary of named parameters to send with the command.

Returns:

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.

Args:

script: The JavaScript to execute.

args:

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’)

find_element

‘Private method used by the find_element_by_* methods. Usage:

Use the corresponding find_element_by_* instead of this.

find_element_by_class_name

Finds an element by class name. Args: name: The class name of the element to find.

Usage:

driver.find_element_by_class_name(‘foo’)

find_element_by_css_selector

Finds an element by ces selector.

Args: css_selector:

The css selector to use when finding elements.

Usage:

driver.find_element_by_css_selector (“*foo”)

find_element_by_id

Finds an element by id.

Args:

id_: The id of the element to be found.

Usage:

driver.find_element_by_ids ‘foo’)

find_element_by_link_text

Finds an element by link text. Angs: link_text: The text of the element to be found.

Usage:

driver.find_element_by_link_text(“Sign In”)

find_element_by_name

Finds an element by name. Angs:

name: The name of the element to find.

Usage:

driver.find_element_by_name(‘foo’)

find_element_by_partial_link_text

Finds an element by a partial match of its link text.

Args:

link_text: The text of the element to partially match on.

Usage:

driver.find_element_by_partial_link_text(“Sign”)

find_element_by_tag_name

Finds an element by tag name.

Args:

name: The tag name of the element to find.

Usage:

driver.find_element_by_tag_name(‘foo’)

Finds an element by xpath.

Args: xpath:

The xpath locator of the element to find.

Usage:

driver.find_element_by_xpath (“//divistd[1]”)

find_elements

“Private method used by the find_elements_by_* methods.

Usage:

Use the corresponding find_elements_by_* instead of this.

find_elements_by_class_name

Finds elements by class name. Args: name: The class name of the elements to find.

Usage:

driver.find_elements_by_class_name(‘foo’)

find_elements_by_css_selector

Finds elements by cos selector.

Args:

css_selector: The css selector to use when finding

elements.

Usage:

driver.find_element_by_css_selector (“*foo”)

find_elements_by_id

Finds multiple elements by id. Angs: id_: The id of the elements to be found.

Usage:

driver.find_element_by_id(‘foo’)

find_elements_by_link_text

Finds elements by link text.

Args: link_text: The text of the elements to be found.

Usage:

driver.find_elements_by_link_text(“Sign In”)

find_elements_by_name

Finds elements by name. Args: name: The name of the elements to find.

Usage:

driver.find_elements_by_name(‘foo’)

find_elements_by_partial_link_text

Finds elements by a partial match of their link text.

Args:

link_text: The text of the element to partial match on.

Usage:

driver.find_element_by_partial_link_text(“Sign”)

find_elements_by_tag_name

Finds elements by tag name. Args: name: The tag name the use when finding elements.

Usage:

driver.find_elements_by_tag_name(‘foo’)

find_elements_by_xpath

Finds multiple elements by xpath. Angs: xpath: The xpath locator of the elements to be found.

Usage:

driver.find_elements_by_xpath (“//divscontains (@class, ‘foo’)]”)

Goes one step forward in the browser history.

Usage:

Usage:

driver. forward()

get

Loads a web page in the current browser session.

get_cookie

Get a single cookie by name. Returns the cookie if found, None if not.

Usage:

driver.get_cookie (“my cookie”)

get_cookies

Returns a set of dictionaries, corresponding to cookies visible in the current session. Usage:

driver.get_cookies()

get_current_window_handle

Returns the handle of the current window. Usage: driver.get_current_window_handle() Note: this method has been deprecated. Please use current_window_handle

property”

get_page_source

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.

Usage:

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.

Args:

filename: The full path you wish to save your screenshot to.

Usage:

driver.get_screenshot as file(‘s Screenshots/foo.png”)

get_window_handles

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

Property

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)

name

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

“strict”.

page_source

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

“strict”.

quit Quits the driver and closes every associated window. Usage:

driver. Quit()

Refreshes the current page. Usage:

driver.refresh()

session_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”.

set_script_timeout

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)

start_client

Called before starting a new session. This method may be overridden

to define custom startup behavior.

start_session

Creates a new session with the desired capabilities.

Args:

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.

switch_to_active_element

Returns the element with focus, or BODY if nothing has focus. Usage:

driver.switch_to_active_element()

switch_to_alert

Switches focus to an alert on the page. Usage:

driver.switch_to_alert()

switch_to_default content

Switch focus to the default frame.

Usage:

driver.switch_to_default content()

switch_to_frame

Switches focus to the specified frame, by index or name.

Args:

index_or_name: The name of the window to switch to, or

an integer representing the index to switch to.

Usage:

driver.switch_to_frame(‘frame name”)

driver.switch_to_frame(1)

Switches focus to the specified window. Args: window_name: The name of the window to switch to. Usage:

driver.switch_to_window(‘main”)

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

“strict”.

window_handles

list() -> new empty list list(iterable) -> new list initialized from iterable’s items

Tags: webdriver (Next Q), python (Next Q)


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

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


Q. WebDriver: get HTTP Response Code

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.


Q. New WebDriver instance per test method?

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.


 Q. Selenium: FirefoxProfile exception Can’t load the profile

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…

http://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)

wget

http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/30.9/linux

x86_64/en-US/firefox-30.6.tar.bz2

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


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

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.


Q. 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):

driver.window_handles


Q. 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:

http://nuget.org/packages/Selenium.Support

Tags: webdriver (Next Q)


Q. Selenium c# Webdriver: WaitUntilElementis Present

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

{

public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInseconds)

{

if (timeoutInSeconds » 9) { var wait = new WebDriverWait(driver, TimeSpan. FromSeconds(timeout InSeconds)); return wait. Until(dry => drv. FindElement(by));

}

return driver. FindElement (by);

I didn’t cache the WebDriverWait object as its creation is very cheap, this extension may be used simultaneously for different WebDriver objects, and I only do optimizations when ultimately needed.

Usage is straight-forward:

var driver = new FirefoxDriver();

driver. Navigate(). GoTourls”http://localhost/mypage”);

var btn = driver. FindElement(By. CssSelector(“#login_button”));

btn. Click();

var employeeLabel

= driver. FindElement(By.css selector(“#VCC_VSL”), 10);

Assert. AreFdual(“Employee”, employeeLabel. Text);

driver. Close();

   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))));

Source   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))); }


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

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.

Q. Selenium WebDriver and DropDown Boxes

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”)));

droplist.selectByVisibleText(“Germany”);


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

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);


Related Pages:

Sample Resume:


 

0 Responses on Selenium Interview Questions"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.