I am new to selenium and started learning it yesterday by watching few videos. I have a doubt regarding how this piece of code works. Please explain.
// I am creating a Object reference for the FirefoxDriver class
FirefoxDriver f=new FirefoxDriver();
//findElementByClassName method is available in FirefoxDriver class. i Can understand this.
f.findElementByClassName("Email").sendKeys("abc");
How does sendkeys("abc")
work? Is it also a method of FirefoxDriver class? I however know that it enters "abc" in the test field. I just wanted to know how it can be used here.
I have tried the same piece of code in a different way. Here, how can the WebElement Class being used along with firefoxDriver class?
FirefoxDriver f=new FirefoxDriver();
WebElement ex= f.findElementByClassName("Email");
ex.sendKeys("abc");
Both these pieces of codes do the required work correctly, but how do they work?
Yes, both of those pieces of code work.
Basically, when you do any findElement
function, it will return a WebElement. A WebElement is an object that points to an HTML element attached to the browser. Then when you sendKeys()
, the driver will then go to that element and type.
WebElements represents as HTML elements.
webdriver.findElement method will fetch the HTML element which satisfies the condition.
The below scenarios web driver will search for the HTML element having class value email and it will return corresponding element and selenium can do further operations on it like click, sendkeys etc...
webDriver.findElement(By.xpath("//*[@class='Email']")
or
webDriver.findElement(By.className("Email")
These are both are exactly the same.You can use any approach.
One added advantage with the second approach is,you can reuse the same 'ex' WebElement to further perform other functions in your code.This provides you reusability.
1st piece of code:
FirefoxDriver f=new FirefoxDriver();
f.findElementByClassName("Email").sendKeys("abc");
-Here,we have two methods cascaded to perform the required function.
-Created 'FirefoxDriver' instance 'f' and then using this instance called its method 'findElementByClassName' which returns a WebElement and then 'sendKeys' fn enters value 'abc' to that web element.
2nd piece of code:
FirefoxDriver f=new FirefoxDriver();
WebElement ex= f.findElementByClassName("Email");
ex.sendKeys("abc");
-Here,two instance,one 'f' for FirefoxDriver and 'ex' for 'WebElement'.
-First,new instance of FirefoxDriver is created and using that we are find WebElement and storing it in 'ex' and using this 'ex' we are performing sendKeys() operation.