Selenium-Revision


What is Parent Child in Xpath…?
Ex1:  //div[@class='abc']/div/div[2]/input
Ex where to use parent child…
Assume a HTML tag does not contains any attributes(ex: name or class or id) to identify in such cases user has to use traverse method in xpath i.e parent child.
Ex2: in Above example parent tag is continuing till child class. '
         Where as in below example from the parent Tag its looking for child Tag, this I the another best example.
//div[@id='glsctl00_mainContent_ddl_originStation1_CTNR'] //a[@value='MAA']

ChroPath is used in Chrome which same as like Firpath in Firefox.

Difference between Relative and Absolute xpath.?
Relative:
Relative doesn't depend on the Parent class.
Ex: //*[@name='q']
Absolute:
Parent to child
Ex: //div[@class='abc']/div/div[2]/input

How to traverse to siblings elements using xpath. ?
Ex: //div[@class='abc']/following-siblling::li[1]

Sibling example: //div[text()='Extras']/following-sibling::div[1]

Parent Child example:
//a[text()='Tomato - Local']/parent::div[@class='col-sm-12 col-xs-7 prod-name']/following-sibling::div[@class='col-sm-12 col-xs-12 add-bskt']//button[@qa='add']

How to traverse back to parent element from child element using Xpath?
This happens only in xpath, its not possible on the CSS.
Ex: User made a operation and verifying still that HTML block(tags from child to parent) is exist or not at that movement it is helpful.
Santosh: my gut feeling is it is possible using parent and child also :)
Syntax ex: //li[@id='abc']/parent::ui

What is the Major difference between Xpath and CSS.?
From xpath we can traverse parent to child and child to parent.
But in css parent to child is possible but child to parent is not possible.
And CSS is faster then xpath to identify the element.

How to identify element with text based.?
//div[text()='selenium']

Identify the element with text based and without tag name..?
//*[text()='selenium']

CSS Selector:
How to identify the element?
Ex1: input[name='q']
Ex2: [name='q']
Ex3: Regular Expression:
Assert.assertTrue(driver.findElement(By.cssSelector("input[id*='SeniorCitizenDiscount']"))

Ex4:  diff between xpath and css
Xpath: //tr/td[2]
Css: tr td:nth-child(2)

How to identify the element using Value.?
This one is using only for the Anchor tags.
//a[@value='MAA']

DropDowns
Static Dropdowns:
By.id()
By.Name()
By.visibleText()

Dynamic Dropdowns:
50. Handle Dynamic dropdowns with Webdriver API(udemy)
Dynamic dropdowns are nothing but, when user clicks on the dropdown button it will display.
Ex: SpiceJet.com
The Departure and Arrival flights will display only when user clicks on the dropdown button.
This is the regular one routine coding.

Auto Suggestive dropdowns:
Makemytrip.com is example for this, type something and select the word.
Driver.findElement(By.xpath("from")).sendKeys("MUM");
Driver.findElement(By.xpath("from")).sendKeys(keys.ENTER);

Driver.findElement(By.xpath("to")).sendKeys("MUM");
Driver.findElement(By.xpath("to")).sendKeys(keys.ARROW_DOWN);
Driver.findElement(By.xpath("to")).sendKeys(keys.ARROW_DOWN);
Driver.findElement(By.xpath("to")).sendKeys(keys.ENTER);

Checkboxes:
Click on the check box: Driver.FindElement(By.xpath("name='abc'")).click;
Get the status(selected or not selected) of the checkbox: Driver.FindElement(By.xpath("name='abc'")).isSelected();
Get the count of the select boxes in current page:
Driver.FindElements(By.xpath("name='abc'")).size;

Radio Buttons:
Syntax: Assert.assertFalse(driver.FindElement(by.xpath("name='abc'").click;

TextButtons:
Alerts Java PopUps:
Selenium WebDriver Java-Pop-Up's:

Assertions:
Ex: Assertions is to make test pass or fail and etc….
Assert.assertFalse(false);
// This will expect false statement. Ex: pick a select box it which should not checked.
Syntax: Assert.assertFalse(driver.FindElement(by.xpath("name='abc'").isSelected));
Assert.assertTrue(True);
// This will expect true statement. Ex: pick a select box it which is already checked.
Syntax: Assert.assertTrue(driver.FindElement(by.xpath("name='abc'").isSelected));
Assert.Equals(statement, comparison);
//this will compare the statement
Syntax: Assert.Equals(driver.FindElement(by.xpath("name='abc'").gettext(), "5 Adults");

Select a date from the calender:
It’s a regular one, nothing special. Get the css/xapth that’s it.

How to get the attributes value..?
//Using below syntax we can get the Attributes of the tags.
Syntax: System.out.println(driver.findElement(By.id("Div1")).getAttribute("style"));

What are the Challenges which you faced in automation.?
Due to recent technologies I observed that isDisable() method is not working in selenium because developers are made like that, to handle that we need to see the changes on tags(ex: Attribute changes in tags).
Syntax: System.out.println(driver.findElement(By.id("Div1")).getAttribute("style"));

14th Nov:
Working with alerts.
How to click/accept on the Alerts?
Driver.switchTo().alert().accept();

How to click on the Cancel Button …?
Driver.switchTo().alert().dismiss();

How to get the text of the alerts?
Driver.switchTo().alert().getText();

Coding Standards:
Variable name always start with Small letter.
Ex: String fullName; or String full;

Class name always start with Big letter.
Class Test{}

Method name always start with.

Debug in Eclipse.?
Click on any line number and add a Toggle Break Point => then run the code 'Debug as' -> 'Java Application'
After executing the program in debug mode the execution will pause at debug Break Point, to run that line user has to click on the 'Step Over' this will execute the Break Point line and then stops at next line.
Click on the 'Resume' Button to execute the remaining steps.
Step Into: this will go into the inside the method.

Learn How to Identify the tag using css.

15th Nov:
Assume there is a website calling BigBasket. You wanted to purchase some vegetables i.e Cucumber but the order(order of the vegetable position or etc..) is inconsistent of the vegetables how to handle it, this will happen always in the realtime and this is a interview question.
Below is the code for it.
//get the list of vegetables first and store it in a list using FindElements feature
List products = driver.findElements(by.cssSelector("h4.Productname"));
For(int i= 0; i
String name = products.get(i).gettext();
If(name.contains("cucumber"))
Driver.findElement(By.name("name='button'")).get(i).click();
Break; // once the element is found stop to stop the forloop
}

//Now the user wants to find Cucumber and Cauliflower. In this case user should save the Vegetables in array list.
String[] vegetableNames = {"Cucumebr", "Cauliflower"};
List products = driver.findElements(by.cssSelector("h4.Productname"));
Int break=0;
For(int i= 0; i
//convert the array to array list.
List Vnames = Arrays.asList(vegetableNames);

String name = products.get(i).gettext();
If(Vnames.contains(name))
Break++;
Driver.findElement(By.name("name='button'")).get(i).click();
//Break; // this break will not work here because after one matching it will stop the forloop to handle it use count
If(break == 2)
Break;
}
//Udemy code added in Eclipse

16th Nov:
Synchronization:
DOM(document object model).
Implicit wait:
Implicit Wait the Driver will keep on listening the DOM weather the element is found or not until the specified time. And it will apply on the driver object.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit wait:
Explicit Wait the Driver will keep on listening the DOM weather the element is found or not until the specified time. And it will apply on the single WebElement.
// explicit wait - to wait for the compose button to be click-able
WebDriverWait wait = new WebDriverWait(drv,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));

Thread.Sleep:
This is for hard pause of the current running program.

Fluent wait(rarely people use this):
Fluent wait is having Polling mechanism. Assume we have given fluent wait of 10seconds and Polling as 2 seconds, in fluent wait it will check the DOM for every 2seconds till completion of 10second.
In realtime very rarely people use this.

19th Nov:
Actions: Actions will provide the mouse operations like Mouse Clicks, Right Clicks, On-Mouse, KeyBoad Events and etc…
Move to specific element i.e On-MouseHover
Syntax and example:
WebDriver driver = new ChromeDriver();
// creating an actions object, now driver will have the capabilities of Actions
Actions a = new Actions(driver);
//the below example is on mouse hover
Actions a = new Actions(driver);
a.moveToElement(driver.findElement(By.xpath("//a[@id='nav-link-prime']"))).build().perform();
driver.findElement(By.xpath("//img[@id='multiasins-img-link']")).click();

How to enter the CAPS Letters in a text box. Ex: SANTOSH
Syntax:
A.moveToElement(Driver.FindElement(By.id("abc"))).click().keyDown(keys.SHIFT).sendKeys("Hello").build().perform();

After Entering the text if you wanted to double click on the text.
A.moveToElement(Driver.FindElement(By.id("abc"))).click().keyDown(keys.SHIFT).sendKeys("Hello").doubleClick().build().perform();

How to Right Click:
a.moveToElement(move).contextClick().build().perform();

How Navigate from Parent window to Child Window..?
Set ids=driver.getWindowHandles();
Iterator it=ids.iterator();
String parentId=it.next();
String childId=it.next();
driver.switchTo().window(childId);
System.out.println(driver.getTitle());
// using below command its navigating to parent window.
driver.switchTo().window(parentId);
System.out.println(driver.getTitle());

Nov 21:
How to work with Frames?
You can switch to the frame using ID/String/WebElement.
Syntax to switch to iFrame:
driver.switchTo().frame(driver.findElement(By.id("abc")));

Find how many Frames are in a webpage.
Sysout(Driver.findElements(By.tagName("iFrame")).size() ); // using this will come to know the size of iFrame.

How to go back to Parent Frame.?
Driver.switchTo().defaultContent();

Drag and Drop a WebElement in  a WebSite:
Actions a = new Actions(driver); // pass the driver object to Action, so that driver will have power to use all action properties.
WebElement drag = driver.findElement(By.id("dragable"));
WebElement drop = driver.findElement(By.id("dropable"));
 a.dragAndDrop(drag, drop).build().perform();

Get me the count of Links in a web Page?
Sysout(driver.findElements(by.tagName("a")).size());

Get the count of Footer Section Links in a WebPage. ?
WebElement Footer = driver.findElements(by.id("footer"));
Sysout(Footer.findElements(By.tagName("a")).size());

Get the count of Footer section first column link size?
//first find the xpath for that column
WebElement footerDriver = driver.findElement(by.id("//div[@id='gf-BIG']//table/tbody/tr/td[1]"));
Sysout(Footer.findElements(By.tagName("a")).size());

How to click on all links in a webpage.?
WebElement footerDriver = driver.findElement(by.id("//div[@id='gf-BIG']//table/tbody/tr/td[1]"));
Int size = Footer.findElements(By.tagName("a")).size();

//Open a page and go back using Navigate method
For(int i=1; i
Driver.findElement(By.tagname("a")).get(i).click();
Driver.Navigate.back();
}

//Open a page in new window using sendKeys
For(int i=1; i
String clickOnlinkTab = keys.chord(Keys.CONTROL, Keys.ENTER);
Driver.findElement(By.tagname("a")).get(i).sendKeys(clickOnlinkTab);
Thread.sleep(2000); //adding a wait
}

//get the title of each window
For(int i=1; i
String clickOnlinkTab = keys.chord(Keys.CONTROL, Keys.ENTER);
Driver.findElement(By.tagname("a")).get(i).sendKeys(clickOnlinkTab);
Thread.sleep(2000); //adding a wait
}
Set abc = driver.getWindowHandles();
Iterator it = abc.Interator();
While(it.hasnext()) {
Driver.switchTo().window(it.next);
}

Session 92/93: How to select a date from Calendar.

Session 93:
Its little difficult but try to understand in free time.
Code is available after 94th Session.

Nov 22:
How to Handle Tables in Selenium?
Practice on 97 and 98.

Nov 23:
Session 103: this session will guide you how to handle the JavaScript DOM.
When Selenium fails to handle, Testers will use the JavaScript DOM.
Ex: Selenium code is trying to get the value of a webelement using driver.findElement(By.xpath("sdf")).getText(); but value is not fetching, in this case we can use the JavaScript DOM method.
driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys("HYDERAB");
driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys(Keys.ARROW_DOWN);
driver.findElement(By.xpath("//input[@id='fromPlaceName']")).sendKeys(Keys.ENTER);
JavascriptExecutor js = (JavascriptExecutor)driver;
String exe = "return document.getElementById(\"fromPlaceName\").value";
String res = (String) js.executeScript(exe);
System.out.println(res);

Session105:
How to Handle Secure certification. It may not required for interview.
By adding below lines it will handle the SSL certification in Browser.
DesiredCapabilities ch=DesiredCapabilities.chrome();
//ch.acceptInsecureCerts();
ch.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
ch.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

//Belows to your local browser
ChromeOptions c= new ChromeOptions();
c.merge(ch);
System.setProperty("webdriver.chrome.driver", "");

What is driver.manage();
Driver.manage() is a method this will manage the browser.
Ex: maximize the window, delete cookies and etc…

How to Maximize the browser.?
Driver.manage().window().maximize();

How to Delete the cookies in the browser.?
By default selenium will open a fresh window, but you still wanted to delete the cookies use below mothod.
Driver.manage().deleteAllCookies();
Apart from above methods, user also can add a cookie also.

User can also delete a specific cookie as well.
Driver.manage().deleteCookieNames("abc");

What is a session cookie..?
A session cookie is best example is gmail or facebook even we close and reopen the browser it will save our login details until we logout from the browser.

How to take screenshots…?
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("C://users//santosh//screenshot.jpg"));
Note: user cannot save the file directly in the C: driver due to security reasons, user should save the file in C:\users\santosh\

How to kill the process, which is running background…?
taskkill /im chromedriver.exe /f

How to validate the Table(HTML) column values are sorted or not.? Famous interview question.
* wheneven doing any work first plat it.
For this problem below are the steps.
  1. Retrieve all the values from the column.
  2. Keep all of them them in a new-array.
  3. Sort the new-array.
  4. Now compare the Retrieved values and new array.   i.e compare the step1 and step2 arrays.
List firstColumnList = driver.findElements(By.cssSelector("tr td:nth-child(2)"));
ArrayList originalList = new ArrayList;
For(int i=1; i
originalList.add(firstColumnList.getText());
}
ArrayList copiedlList = new ArrayList;
For(int i=1; i < originalList(); i++){
copiedlList.add(originalList.get(i));
}
//sorting the collection list
Collections.sort(copiedList);
//now checking them
Assert.assertTrue(origianlList.equals(copiedList));

How to fetch the values using findElements and print them using sysout.?
List firstColumnList = driver.findElements(By.cssSelector("tr td:nth-child(2)"));
For(int i=1; firstColumnList.size(); ++){
Sysout(firstColumnList.getText());
}

Selenium GRID..?
This will work like Hub and Node.
Ex: when tester wants to execute the tests on different machine at that time we use Hub and Node concept.
Using node and hub concept we can divide the testcases distribute to different machines by doing this our testcase execution will decreases.
Most of the big companies are using this concept.
Commands in Hub Machine
1.Setting Up Hub:
java -jar selenium-server-standalone-2.44.0.jar -role hub
2.Validating Hub started
Commands in Node Machine
3.Accessing Hub from Node Machine
4.Registering Node with Hub
Java –jar selenium-server-standalone-2.44.0.jar –role webdriver –hub http://iporhostnameofHub:4444/grid/register -port 5566
or Start node using Chrome.
Java -Dwebdriver.chrome.driver="c:\chromedriver.exe" –jar selenium-server-standalone-2.44.0.jar –role webdriver –hub http://iporhostnameofHub:4444/grid/register -port 5566

Code:
public class Testparallel {
//protected ThreadLocal threadDriver = null;
public static void main(String[] args) throws MalformedURLException {
WebDriver driver;
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.BINARY,new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe").getAbsolutePath());
driver = new RemoteWebDriver(new URL("http://192.168.0.106:5566/wd/hub"), capabilities);
driver.get("http://google.com");
System.out.println(driver.getTitle());
}





Others
Exceptions/Errors:
NoSuchElementException: Unable to locate Element
The above error will occur when the element is not present in the run time.

Whenever we are getting the value from FindElement that format is String, you have to convert it as Integer using below method.
Int valInteger = Integer.parseInt(value);

What is the disadvange of Selenium?
If the Webelement is in hidden mode at that time selenium cannot get the value of it. In this case we have to use JavaScript DOM.


.

Comments

Popular posts from this blog

Handling Excel

JavaInterviewPrograms