Read more
- Home
- Element Locators
- Tips & Tricks
- Handle Upload Dialog
- Browser Functions
- Selenium Grid
- Handling SSL Certificates
- Code snippet ready-made...
- EventFiringMouse in Selenium webdriver
- log4j config
- Reading HTTP response using java
- Read JSON object using java
- Quick Reference - Selenium Interview Questions
Tips & Tricks
Element Locators:
Here are some of the easiest way with element locators to select web element I would like to share, if you didn't go thorough the sections Element Locators already I suggest to see once.
Apparently, we need to find so many web elements to do some actions on it in our tests, and it also possible that an attribute includes space in it, so to remove such spaces we can use the following methods
for example: I have a tag like this, <div data-jiis="bp" id="cnt" class=" mdm">...</div>
if we want to select this 'div' tag using 'class' attribute then in
X-Path: //div[normalize-space(@class)='mdm'] should work, and in
CSS-Selector: div[class$='mdm']; will work.
DOM: document.getElementsByClassName(' mdm')
In X-path, we have a method called normalize-space(string) will remove the space at beginning and at end from the string.
Css-selector div[class$='mdm'] searches the div tag that has class attributes which ends with string mdm
The more we practice with these scenarios the better we do and the easiest way and most of the tools we have already available. The one such tool is chrome browser, to practice these methods. To open in chrome follow the steps
1)Open chrome browser, and launch any web site, for example, https://www.google.com
2)Enter any search word (Selenium software). Now press F12 (function key 12) on your keyboard,
3)Finally, press Esc (escape) key on your keyboard, this brings you console
On the console, if you want to test the above query mentioned in X-Path you have type between $x(""), i.e., it looks like $x("//div[normalize-space(@class)='mdm']"), and in CSS-selector $$(""), i.e,. it looks like $$("div[class$='mdm']"), and in DOM you have write as it is.
There are other tools also available, to find element locators in different browsers for fire-fox we have bugzilla or DOM Inspector and for Internet Explore it is IE WebDeveloper. We may find many other tools like such, but its depend on our own interest, we have to choose one.
Q) How to debug element locators in IE..??
A) We need to install developer tool, and by default IE from version 7 it is available with in browser and to enable it use F12 key. After which to find an element using css locator then type the following code, for example
document.querySelector("a[name='overridelink']")The result would be display as follows,
>> document.querySelector("a[name='overridelink']")http://localhost/index.do{
charset : "",
coords : "",
hash : "",
host : "localhost",
hostname : "localhost",
href : "http://localhost/index.do",
hreflang : "",
name : "overridelink",
pathname : "/index.do"
port : "80"
...
}
Add to watch
Quick Popup Question
Q) When to use Server jar files and Server stand alone jar..??
A) i) The standalone-server Jar is used to start a remote Node server or Grid 2 server. Some people start the server from their own code, but that is really the only time you would use that jar in your program.
ii) The Selenium Java Jar file is if you want to run WebDriver directly, or as a client using RemoteWebDriver talking to a Node or Grid 2 server. This is the jar you will definitely be using for writing your Web Driver code.
Firefox Setup while Handling SSL Certificate:
Q) How to see which firefox browser profile is currently using..?A) In Firefox browser, navigate to Help -> Troubleshooting Information
We should see a subheading with name 'Application Basics' in bold and there we go..
Find a button "Show Folder" right adjacent to 'Profile Folder'
Q) How to suppress the saveAs dialog in selenium webdriver..??
A) Well, this can be achieved once after the firefox profile is set properly as explained here. Then once firefox profile instance available the set the preferences as follows
ffProfile.setPreference("browser.helpApps.neverAsks.openFile", "application/jar");this browser.helpApps.neverAsks.openFile accepts comma-separated list of MIME types to open directly without asking for confirmation. Default value is an empty string. find doc here
Element Locators
Element Locators
There are several techniques we have to locate elements. I believe we will get familiar on these only
when make our hands dirty with practicing on a web page. Of course, we should have a basic knowledge on HTML, CSS and Java script before getting awareness on the following terms, in brief the ways we use to find elements are
1) Identifiers
2) Name
3) XPath alternatively click for more info
4) Link Text
5) DOM
6) CSS Selectors alternatively click for more info
Let us have a quick over-view on these terms from the following sample HTML code
In our example, to access 'Username' element we can use the following procedure in DOM
document.getElementById('userid')
Q) I have given the correct String value, but still element is not finding
A) The possible answer and I have seen is, our eyes sometimes mislead with letter '1'(one) to alphabetical letter 'l'. That is,
If the element attribute value is something like, id='1a' (read as, one a) but we may type as id='la' (read as, el a)
The other mistake is we may miss the spaces on the begin / end of an attribute, that is if id='ul ' in HTML page but we may type as id='ul', to avoid this common error we have to trim the value.
For Tip & Tricks on these element selections click on the link or click to download pdf copy. More info from an official reference link
<html>
<title> Selenium Tutorial Page</title>
<head>
<!-- script code goes here -->
</head>
<body>
<fieldset>
<p id='a' name='para'>
Username: <input type='text field' name='username' id='userid'/></br>
Password: <input type='text field' /></br>
<a href='http://seleniumbee.blogspot.com'> Submit </a>
</p>
</fieldset>
</body>
</html>
> Identifiers: From the above code, HTML 'input' tags has an attribute called 'id' is called as identifiers which is used to identify the text fields, i.e., 'id' is an attribute
For ex: In Selenium, to find an element with identifiers, we will use the following code
driver.findElement(By.id("userid")); // I am assuming driver is initialized with a browser object
driver.findElement(By.id("userid")); // I am assuming driver is initialized with a browser object
> Name: Similarly, in order to find an element with 'name', we can use name attribute in the 'input' tag of html page
For ex: driver.findElement(By.name("username"));
> XPath: X-path is an easy way to find an element in the entire HTML document. The major scenarios when one has to go with X-path is,
If the desired element is not provided by either an 'id' nor 'name' attribute for a tag, then we can achieve this by using xpath absolute path or relative (parent or ancestor) to an element that has id or name
From our above HTML example, to find an element 'Username' xpath notation, we can do it in the following ways
If the desired element is not provided by either an 'id' nor 'name' attribute for a tag, then we can achieve this by using xpath absolute path or relative (parent or ancestor) to an element that has id or name
From our above HTML example, to find an element 'Username' xpath notation, we can do it in the following ways
i) driver.findElement(By.xpath("//input[@id='userid']")); // or
ii) driver.findElement(By.xpath("/html/body/fieldset/p/input[@id='userid']"));
From the above two statements, second method is called an absolute way, which is not recommend. Whereas, the first one called a general way of xpath usage, in xpath '//' indicates where ever in the HTML document from the root node ('html')
Now, to find 'password' field, we don't have any 'id' or 'name' attributes, in such scenario's we have to find the nearest element to password element that any one of these attributes, i.e.,
xpath: //p[@id='a']/input[2] should works.
Now, to find 'password' field, we don't have any 'id' or 'name' attributes, in such scenario's we have to find the nearest element to password element that any one of these attributes, i.e.,
xpath: //p[@id='a']/input[2] should works.
Note: Here tag 'p' has two children in it 'username' and 'password' so in order to select 'password' field we are giving '[2]' after input tag, beacuse the result yields an array of input elements with length two.
*** In some cases, we need to find an element by specifying two attributes to make it unique, then we have to use the following way
//p[@id='a'][@name='para']
*** Sometimes, it happens to identify elements that contains exact text. That is, if we have two web elements, say
1) <div class="item">max_dses_and_dps_share</div>
2)<div class="item">share</div>
and now we want to identify the element that contains text as 'share' in it, then usual way to do is using contains() method of xpath,
//*[contains(text(), 'share')]
but the problem here is, we get two elements as a result. So, what if I want to get the element that has exact match on share but not part of text.?
The following ways can solve the problem
method #1) //*[text()[normalize-space(.)='share']] OR
method #2) //*[.='share']
method #1 is actually a way of trimming spaces.
*** Sometimes, it happens to identify elements that contains exact text. That is, if we have two web elements, say
1) <div class="item">max_dses_and_dps_share</div>
2)<div class="item">share</div>
and now we want to identify the element that contains text as 'share' in it, then usual way to do is using contains() method of xpath,
//*[contains(text(), 'share')]
but the problem here is, we get two elements as a result. So, what if I want to get the element that has exact match on share but not part of text.?
The following ways can solve the problem
method #1) //*[text()[normalize-space(.)='share']] OR
method #2) //*[.='share']
method #1 is actually a way of trimming spaces.
> Link Text: is mostly used for hyper links / anchor tags with a text, in our example 'Submit' is an anchor tag and to find this element we can use the following way,
driver.findElement(By.linkText("Submit")); // we have an already method linkText(String) in //Selenium webdriver API
> DOM: Document Object Model, can be accessed using JavaScript. In selenium, JavaScript Executor is an interface and implemented by dependent driver classes and used to execute Javascript codedriver.findElement(By.linkText("Submit")); // we have an already method linkText(String) in //Selenium webdriver API
In our example, to access 'Username' element we can use the following procedure in DOM
document.getElementById('userid')
> CSS Selector: Cascading Style Sheet selectors are the best and recommended way to locate elements in the HTML document due to its quickness and can find the most complicated objects naturally
To find, tag 'p' in our example, with attribute 'id', its that simple with three letters in CSS selector as follows
To find, tag 'p' in our example, with attribute 'id', its that simple with three letters in CSS selector as follows
driver.findElement(By.cssSelector("p#a")); //Assume driver is an initialized browser object
Question & Answers:
Since I can't predict all the possibilities of errors you are facing, so please comment your queries.
The most common error usually I see with people are presented as a question belowQuestion & Answers:
Since I can't predict all the possibilities of errors you are facing, so please comment your queries.
Q) I have given the correct String value, but still element is not finding
A) The possible answer and I have seen is, our eyes sometimes mislead with letter '1'(one) to alphabetical letter 'l'. That is,
If the element attribute value is something like, id='1a' (read as, one a) but we may type as id='la' (read as, el a)
The other mistake is we may miss the spaces on the begin / end of an attribute, that is if id='ul ' in HTML page but we may type as id='ul', to avoid this common error we have to trim the value.
For Tip & Tricks on these element selections click on the link or click to download pdf copy. More info from an official reference link
Home
Selenium Kick Start:
Selenium is an open source and one can find its official web site hereYou are on this page because you are interested in using selenium tool. Apparently, the key aspects of selenium tool to go when you are interested in the following requirement
1. Application Under Test (AUT) is a web based which needs to be tested on multiple browsers
2. Tests has to perform on parallely when time is a main constraint
3. Needs to execute tests on remote machine, perhaps on developer environment or client machine
Inject to brain: Alright, before going to start I would like to say that, I am not an expert to explain about selenium on my finger tips, instead would like to share my experience and the common mistakes and solutions I passed through. Also, note that I am going to use java as my language as part of code implementation in the examples you see.
The most of the functions we discuss are available on selenium's official API , for example, if you find terms WebDriver or WebDriverBackedSelenium, Actions, ChromeDriver and so on
Before explaining further, let me start a very simple program, that is will see how to launch browser
Program #1 :
I have named class name as Setup and its in default package
// Importing respective packages for drivers
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Setup {
public static void main(String[] args) {
//Created firefox instance
WebDriver driver = new FirefoxDriver();
// Magics happens here to launch firefox driver by calling 'get(String url)' method
driver.get("http://www.google.com");
}
}
Lets see the possible beginners mistakes:
1) On console I am seeing following an error:
Q) How to resolve?
A) > You can install fire fox browser
1) On console I am seeing following an error:
Exception in thread "main" org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH.
Make sure firefox is installed. OS appears to be: WIN8
Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
System info: os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.2', java.version: '1.7.0_45'
Driver info: driver.version: FirefoxDriver
which means, we don't have a fire fox browser installed in our computer
which means, we don't have a fire fox browser installed in our computer
Q) How to resolve?
A) > You can install fire fox browser
> You can change the browser type to chrome or IE
Q) How can I create Chrome or IE browser object / how can I launch browser other than default fire fox browser?
A) > Before creating other browser objects other than default fire fox browser we need to set path to respective browser executable file. We will see this in the following code snippet
// Importing respective packages for drivers
// Importing respective packages for drivers
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Setup {
// Chrome executable path
private final static String CHROME_PATH = "C:\\Users\\<user name>\\Downloads\\Selenium\\chromedriver.exe" ;
public static void main(String[] args) {
// Setting here system properties for chrome browser by specifying chrome executable path
System.setProperty("webdriver.chrome.driver", CHROME_PATH);
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
}
}
Q) Where can I find these executable drivers
A) Answer is simple, selenium is an open source so developer are providing these files too, here.
A) Answer is simple, selenium is an open source so developer are providing these files too, here.
2) I have given everything fine, but page is not loading with URL and giving the following error on console
FAILED: test
org.openqa.selenium.WebDriverException: unknown error: unhandled inspector error: { "code":- 32603,"message":"Cannot navigate to invalid URL"}
(Session info: chrome=27.0.1453.116)
(Driver info: chromedriver=2.1,platform=Windows NT 6.1 SP1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 158 milliseconds
Build info: version: '2.35.0', revision: 'c916b9d', time: '2013-08-12 15:42:01'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_45'
Session ID: 1ca2288cf0164b957c20be8514e1fb5c
Driver info: org.openqa.selenium.chrome.ChromeDriver
Perhaps, we have missed the 'http://' in the URL for example driver.get("www.google.com").
Subscribe to:
Posts (Atom)