Selenium Notes and interview Questions
Selenium Architecture:
Selenium 3:
Selenium Client Library(Java,JS,python)----->JSON wire protocol---->WebDrivers--->browsers
Selenium 4:
Selenium client Library(Java,JS,Python)---->W3C Webdriver protocol--->WebDrivers---->Browsers
Driver launch:
// System.setProperty(“webdriver.chrome.driver”,”safjsanf.exe”);--->system set property not required,below code itself it launching the browser
WebDriver driver=new ChromeDriver();
WebDriver driver=new EdgeDriver();
WebDriver driver=new FireFoxDriver();
WebDriver driver=new SafariDriver()
//URl Launch
driver.get(“https://www.google.com”);
//Maximize
driver.manage().window().maximize();
//Locate Elements:
driver.findElement(By.id,name,cssSelector,className,linktext,partialLinkText,tagName,xpath
// Click method
webelement.click();
//clear method:
webelement.clear()
//nested findElement
WebElement element=webelement.findelement(By.id(““)).click() ;
//Sending value to the text box
webelement.sendKeys(“sangar” Bro)
//getting value of particular attribute:
String value=webElement.getAttribute(“value”);
// get Particular Text from webpage:
String text=webElement.getText();
//Check enabled:
boolean status=webelement.isEnabled();
// get location of button:
Point point=webelement.getLocation()
int x=point.getX()
int y=point.getY();
// get CSS value
String colu
// get size of button
Dimension dim=webElement.getSize()
int hight=dim.getHeight();
int width=dim.getWidth();
//Handling dropdowns:
By using select class
Select select=new Select(WebElement of Dropdown);
select.selectByIndex(1);
select.selectByValue(“SAngar”);
select.selectByVisibleText(“sangar”);
select.deselectByIndex(0);
select.deSelectByValue(“sanga”);
select.deSelectByVisibleText(“sangar”);
select.deSelectAll();
select.getFirstSelectedOption();
List<WebElement> allOptions=select.getOptions();
Handling Alert:
webElement.click();
Alert alert=driver.switchTo().alert()
alert.accept();
alert.sendKeys(“sangar”);
alert.dismiss();
String text=alert.getText();
//working with radio button,check boxes
webelement.isSelected();
webElement.click();
// window handling:
String parentWindow=driver.getWindowHandle();---->Returns parent window id
Set<STring> allWindows=driver.getWindowHandles();=------>contains all window ids.
for(String id:allWindows){
driver.switchTo().window(id);
if(driver.getTitle().contains(“Google”){
break;
}}
//perofrm operations in new window,then switch to old
driver.switchTo().window(oldWindow);
//close and quite
driver.close()---->only close current window
driver.quite()--->close entire browser
Handling Frames:
//count of frames can be retrieved through below way
List<WebElement> li=driver.findElements(By.tagName('iFrame'));
for(WebElement ele:li){
firstFrame=li.getText();
}
driver.switchTo().frame(0)---->here we can give index or frame name or frame id or frame element
driver.switchTo().defaultContent()---->Reseting the content and swtich back to non frame home page
XPAths:
Absolute and relative xpath:
Absolute:/html/head/body/
Relative://tagname[@attribute='value']
Strategies:
1.Locate with known attribute--->//*[@id='q']
2.Locate with known tag&attribute--->//tag[@id='q']
3.Locate with known visible text--->//*[text()='sangar']
4.locate with part of visible text---->//*[contains(text(),'sangar')]
5.Locate with multiple attributes---->//*[@id='qa][@tag='snagar'][@class='varial']
6.Locate with starts with------------->//*[starts-with(text(),'sangar')]
//*[normalise-space()=' asdnasn safjan ')]
7.Locate with contains in attribute---->//*[contains(@class,'partial')]
8.Locating parent------------>//*[@id='sanga']/parent::div
9.locating child----------->//*[@id='sangar']/child::div
10.locating ancestor------------>//*[@id='sangar']/ancestor::div
11.Locating following------------>//*[@id='sangar']//following::div
12.Locating preceding--------------->//*[@id='sangar']//preceding::div
13.Locating follwoing-sibling-------->//*[@id='sangar']//following-sibling::div
14.lcoating preceding-sibling---------->//*[@id='sangar']//preceding-sibling::div
Drag and Drop:
Actions action=new Actions(driver);
action.clickAndHold(fromElement).moveToElement(to).release().build().perform()
action.contextClick().buil().perform();
action.contextClick(WebElement).buil().perform();
action.doubleClick().build().perform()
action.doubleClick(WebElement).build().perform()
actions.click(Webelement).build().perform();
action.dragAndDrop(from,to).build().perform()
actions.sendKeys(“Sad”);
// working with selectable
actions.keyDown(Keys.CONTROL).click(first).click(second).click(third).keyUp(Keys.CONTROL).build().perform();
//tool tip
webElement.getAttribute(“title”);
// Auto complete:
driver.findElement(By.name(“searchBox”).sendKeys(“Ind”);
List<WebElement> li=driver.findElements(By.xpath(“//li”));
for(WebElement ele:li){
if(ele.getText().equalsIgnoreCase(”India”)){
ele.click();
break;
}}}}
// verify file download and check
webElement.click();
File file=new File(“c//downloads”);
File[] files=file.listFiles();
for(File file:files){
if(file.getName().contains(“Ecc.xlsx”){
sysout(“File downloaded successfully”);
break;
}}}}
// uploading a File
String filePath=”snc.xlsx”;
//if this element is in input tage, sometimes normal sendkeys will work
StringSelection selection=new StringSelection(filePath);
ToolKit.getDefaultToolKit().getClipboard().setContents(selection,null);
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_Control);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_Control);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
or
new Actions(driver).keyDown(Keys.control).sendKeys(“v”).keyUp(Keys.Control).KeyDown(Keys.ENTER).KeyUp(Keys.ENTER).build().perform();
// find broken image from the webpage
1.one way
List<WebElement> list=driver.findElements(By.tagName(“img”));
for(WebElement ele:list){
String link=ele.getAttribute(“src”);
if(link==null||link.isEmpty()){
continue;
}URL url=new URL(link);
HTTPURlConnection connection=(HTTPURLConnection)url.openConnection();
connection.setRequestMethod(“GET”);
connection.connect();
if(connection.getResponseCode()!=200){
sysout(“Broken image”+link);
2.second way:by fetching natural width of the image
List<Webelements> li=driver.findElements(By.tagname('img”);
for(WebElement element:li){
if(element.getAttribute(“naturalWidth”).equals(“0”){
sysout(this is broken image”+element);
Broken Links:
List<WebElement> ele=driver.findElements(By.tagName(“a”));
for(WebElement e:ele){
String link=e.getAttribute(“href”);
driver.get(link);
driver.getTitle().equals(404).--->this is broken link
Selenium Exceptions:
PArent : WebDriver Exception
NoSuchElementException
StaleElementReferernceException--->retry,relocate,expliicit wait
UnhandledAlertException
NoAlertPresentException
InvalidElementStateException
ElementNotVisibleException
ElementNotSelectable
NosuchFrame
NoSuchSession
NoSuchWindowHandle
timeoutException
SessionNotCreated
JavaScriptExceution
ElementClickInterceptedException
Waits:
Implicit wait:
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
We cant set any conditions
and it is not suitable for invisible,not interactable elements
Explicit Wait:Allow us to set the webdriver to wait for some conditions
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(30));
WebElement elemenbt=wait.until(ExpectedConditions.elementToBeClickable(element);
element.click();
ExpectedConditions:
elementToBeClickable
elementToBeSelected
presenceOfElementLocate
texttoBePresentInElement
refreshed
Fluent Wait:
we can set some polling time,handle the exception
Wait<WebDriver> wait=new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(20).pollingEvery(Duration.ofseconds(5))
.ignoring(Exception.class);
WebElement element=wait.until(driver->driver.findElement(By.id('q'));
element.click();
GET | Navigate().to() |
|---|---|
not stores the huistory | stores the history |
catn go back,refresh,forward | can go forward,back,refresh |
Screenshot Taking:
1.using TakesScreenshot interface
TakesScreenshot ts=(TakesScreenshot) driver;
File file=ts.getScreenshotAs(OutputType.FILE);
File dest=new File(“sanga.jpeg”);
FileUtils.copyFile(file,dest);
or
FilHandler.copy(file,dest);
2.Using robot class:
Robot robot=new Robot()
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect=new Rectangle(dim);
BufferedImage img=robot.createScreencapture(rect);
File file=new file(“sangar.png”);
ImagoIO.write(img,”png”,file);
Different ways to Refresh the browser:
1.driver.get(driver.getCurrentUrl());
2.driver.navigate().to(“sanga.com”)
driver.navigate().refresh();
3.using JS executor:
JavaScriptExecutor js=(JAvascriptExecturo) driver;
js.executeScript(“location.reload()”)
or
js.executeScript(“history.go(o)”);
4.Using Robot class:
Robot robot=new Robot();
robot.KeyPress(KeyEvent.VK_F5);
robot.KeyRelease(KeyEvent.VK_F5);
Different ways to maximize:
1.using chrome arguments
ChromeOptions options=new ChromeOptions();
options.addArguments(“--start-maximized”);
2.driver.manage().window().maximize();
3.driver.manage().window().setSize(new Dimension(300,400));
Launch browser:
1.System.setProperty(“webdriver.chrome.driver”,”sjasd.exe”);
2.WebDriverManager.chromeDriver().setup();
3.WebDriver driver=new EdgeDriver();
4.by setting driver in environment variable
Handling authentication Popup:
1.If it is web based popup we can simply use Alert to handle it.
Alert alrert=driver.switchTo().alert();
alert.sendKeys(“Sangar”+Keys.TAB+”SAngar”);
alert.accept();
2.Window based popup we can use third party tools like AutoIT
1.We have to download autoit editor
2.once the popup came,we have to locate the username box,password box using autoITelement locator
3.it will give some title,class,instance by using that we have write the scritp
4.first find username box--->ControlFocus=(“Class”,””,”Edit1”)
5.set the username--->Control SetText=(“Class”,””,”Edit1”,”sangar”)
6.second find password box--->ControlFocus=(“Class”,””,”Edit1”)
7.second set passwor--->ControlSetText=(“Class”,””,”Edit1”,”Sangar@11”);
8.set the click button-->Control click=(“Class”,””,”Button1”)
Upload scernario:
1.set the file name--->Control SetText=(“Class”,””,”Edit1”,”pathof file.resume.txt”)
2.set the click open-->Control click=(“Class”,””,”Button1”)
9.Save this script as AutoIT file
10.right click -->Compile script x64
11.Now refer this file
RunTime.getRunTime().exec(“sdja.exe”);
3.passing username password along with URl itself
Ways to Press Enter:
1.driver.findElement(By.xpath(““//a”)).sendKeys(“Sangar”+Keys.ENTER);
2.element.sendKeys(“Sangar\n”)
3.element.submit();
4.new Robot().keyPress(KeyEvent.VK_ENTER),new ROBot().KeyRelease(KeyEvent.VK_ENTER);
Switch to Active Element:
driver.switchTo().activeElement().sendKeys(“Samgar”);
scrolling:
1.Using JS Executor:
JavaScriptExecutor js=(JavaSCriptExecutor)driver;
js.executeScript(“window.scroll(0,-450)”,””)-------->scroll up
js.executeScript(“window.scroll(0,450)”,””)--------->scroll down
js.executeScript(“0,document.body.scrollHeight”,””);------------>Bottom of the page
js.executeScript(“window.scroll(0,0)”);-------------->scroll to top
js.executeScript(“arguments[0].scrollIntoView(true)”,element);
2.Using robot:
new Robot().keyPress(KeyEvent.PAGE_down);
new Robot().keyRelease(KeyEvent.PAGE_down);
new Robot().keyPress(KeyEvent.PAGE_UP);
new Robot().keyRelease(KeyEvent.PAGE_UP);
MouseHover:
Actions actions=new Actions(driver);
actions.moveToElement(element).build().perform();
Text underlined:
driver.findElement(By.id(“sangar”)).getCSSValue(“text-decoration“);
Assert vs Verify:
Assert-->once assert fails next line of code wont execute
Verify-->Softassert--->if Assert fails it allow us to execute next lines of codes
SoftAssert assert=new SoftAssert();
assert.asserEquals(String actual,String expected,String message);
JUnit assertion:
Assert.assertEquals(String message,String expected,String actual);
Sending values:
1.js.executeScript(“arguments[0].value='sangar'“,searchBox);
2.using robot
driver.swtichTo().activeElement();
Robot
Launch URL:
js.executeScript(“window.location='https:www.google.com”)
Comments
Post a Comment