Selenium Material

download Selenium Material

of 10

Transcript of Selenium Material

  • 7/25/2019 Selenium Material

    1/10

    [email protected]

    Questions & Answers

    Commands

    Create a instance for All Browsers

    For Firefox

    WebDriver driver = new FirefoxDriver();

    For Chrome

    System.setProperty("webdriver.chrome.driver", "H:\\chromedriver.exe");ChromeDriver driver = new ChromeDriver();

    For IE

    System.setProperty("webdriver.ie.driver", "H:\\InternetExplorerDriver.exe");

    InternetExplorerdriver = new InternetExplorerDriver();

    Applying Implicit wait in webdriver

    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

    Command To Open URL In Browser

    driver.get("URL");

    Clicking on any element or button of webpage

    driver.findElement(By.id("object_id")).click();Store text of targeted element in variable

    String dropdown = driver.findElement(By.tagName("select")).getText();

    Typing text in text box or text area

    driver.findElement(By.name("fname")).sendKeys("My First Name");

    Applying Explicit wait in webdriver with WebDriver canned conditions

    Example 1

    WebDriverWait wait = new WebDriverWait(driver, 15);

    wait.until(ExpectedConditions.textToBePresentInElementLocated(By

    .xpath("//div[@id]"), "Time left: 7 seconds"));

    Descirption 1

    Above 2 syntax will wait for till 15 seconds for expected text

    Time left: 7 seconds to be appear on targeted element

    Example 2

    WebDriverWait wait = new WebDriverWait(driver, 10);

    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(

    By.id("someid")));

    Description 2

    Wait 10 seconds for the element to be clicked

    Get page title in selenium webdriver

    driver.getTitle();

    Get Current Page URL In Selenium WebDriver

    driver.getCurrentUrl();

    To get the source page of the url

    driver.getPageSource() - Returns the source code of the page as a String value

    Get domain name using java script executor

    Command

    JavascriptExecutor javascript = (JavascriptExecutor) driver;

    String CurrentURLUsingJS=(String)javascript.executeScript

    ("return document.domain");

    Descirption

    Above syntax will retrieve your software application's domain name usingwebdriver's java script executor interface and store it in to variable

    Generate alert using webdriver's java script executor interface

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    2/10

    [email protected]

    Command

    JavascriptExecutor javascript = (JavascriptExecutor) driver;

    javascript.executeScript("alert('Test Case Execution Is started Now..');");

    Descirption

    It will generate alert during your selenium webdriver test case execution

    Selecting or Deselecting value from drop down / Listbox in selenium webdriver

    SelectingCommand 1 - selectByVisibleText

    Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));

    mydrpdwn.selectByVisibleText("Audi");

    Command 2 - selectByValue

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    listbox.selectByValue("Italy");

    Command 3 - selectByIndex

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    listbox.selectByIndex(0);

    DeselectingCommand 1 - selectByVisibleText

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    listbox.deselectByVisibleText("Russia");

    Command 2 - selectByValue

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    listbox.deselectByValue("Mexico");

    Command 3 - selectByIndex

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    listbox.deselectByIndex(5);

    Command 4 - Deselect All

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    listbox.deselectAll();

    Is Multiple Select

    Select listbox = new Select(driver.findElement(By.xpath("//select[@name]")));

    boolean value = listbox.isMultiple();

    Navigate to URL or Back or Forward in Selenium Webdriver

    4 Commands

    driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");

    driver.navigate().back();

    driver.navigate().forward();

    driver.navigate().refresh();

    Capturing entire page screenshot in Selenium WebDriver

    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

    FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));

    To get the location of the object on the web page?

    WebElement ele_1=driver.findElement(By.id("draggable"));

    Point p1=ele_1.getLocation();

    System.out.println("X : "+p1.getX());

    System.out.println("Y : "+p1.getY());

    What are the Mouse events in Actions class?

    clickAndHoldDescription

    Click more than one elements one by one

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    3/10

    [email protected]

    Example

    WebElement ele_1=driver.findElement(By.xpath("//*[@id='selectable']/li[1]"));

    WebElement ele_2=driver.findElement(By.xpath("//*[@id='selectable']/li[2]"));

    WebElement ele_3=driver.findElement(By.xpath("//*[@id='selectable']/li[3]"));

    Actions ac= new Actions(driver);

    ac.clickAndHold(ele_1).clickAndHold(ele_2).clickAndHold(ele_3).

    build().perform();ac.release().perform();

    dragAndDropBy

    Description

    Move a element to other element's location

    Example

    WebElement ele_1=driver.findElement(By.xpath("//*[@id='sortable']/li[1]"));

    WebElement ele_7=driver.findElement(By.xpath("//*[@id='sortable']/li[7]"));

    Actions ac= new Actions(driver);

    Point ele_7_pos=ele_7.getLocation();

    ac.dragAndDropBy(ele_1,ele_7_pos.getX(), ele_7_pos.getY()).build().perform();ac.release().perform();

    dragAndDrop

    Description

    Drag one element, and drop It on the frame or other object

    Example

    WebElement ele_1=driver.findElement(By.id("draggable"));

    WebElement ele_2=driver.findElement(By.id("droppable"));

    Actions ac= new Actions(driver);

    ac.dragAndDrop(ele_1, ele_2).build().perform();

    ContextClick()

    Description

    Right click on web page, and click "view page source"

    Example

    WebElement ele_1=driver.findElement(By.xpath("//*[@id='sortable']/li[1]"));

    Actions ac= new Actions(driver);

    ac.contextClick().sendKeys(Keys.DOWN).sendKeys(Keys.DOWN).

    sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).build().perform();

    moveToElement()

    Description

    Handling Dropdown menu - move to mouse cursor on a particular element,

    then only the menu will be appear, then click the sub-menu

    Example

    Actions actions = new Actions(driver);

    WebElement menuName = driver.findElement(By.id("some_id"));

    actions.moveToElement(menuName);

    actions.perform();

    Double Click

    Actions act = new Actions(driver);

    act.doubleClick(webelement);

    send ENTER/TAB keys through Actions in WebDriver

    Use Actions class to press keysActions act = new Actions(driver);

    For ENTER

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    4/10

    [email protected]

    act.sendKeys(Keys.RETURN);

    For TAB

    act.sendKeys(Keys.ENTER);

    Handling Multiple Windows In Selenium WebDriver

    Get All Window Handles

    Set AllWindowHandles = driver.getWindowHandles();

    Extract parent and child window handle from all window handlesString window1 = (String) AllWindowHandles.toArray()[0];

    String window2 = (String) AllWindowHandles.toArray()[1];

    Use window handle to switch from one window to other window

    driver.switchTo().window(window2);

    Enable/Disable Textbox During Selenium Webdriver Test Case Execution

    Command

    JavascriptExecutor javascript = (JavascriptExecutor) driver;

    String todisable =

    "document.getElementsByName('fname')[0].setAttribute('disabled', '');";

    javascript.executeScript(todisable);String toenable =

    "document.getElementsByName('lname')[0].removeAttribute('disabled');";

    javascript.executeScript(toenable);

    Descirption

    It will disable fname element using setAttribute() method and enable lname

    element using removeAttribute() method

    Highlighting Elements

    WebElement element2 = driver.findElement(By.id("Value"));

    JavascriptExecutor javascript = (JavascriptExecutor)driver;

    javascript.executeScript("arguments[0].setAttribute('style', arguments[1]);",

    element1, "color: blue; border: 2px solid blue;");

    Submit() method to submit form

    driver.findElement(By.xpath("//input[@name='Company']")).submit();

    Handling Alert, Confirmation and Prompts Popups

    To store alert text

    String myalert = driver.switchTo().alert().getText();

    To accept alert

    driver.switchTo().alert().accept();

    To dismiss confirmation

    driver.switchTo().alert().dismiss();

    How to get typed text from a textbox ?

    String typedText = driver.findElement(By.xpath("xpath of box")).getAttribute("value");

    (or)

    String typedText = driver.findElement(By.xpath("xpath of box")).getText();

    How do you get the current page URL ?

    driver.getCurrentUrl();

    To identify a text present on the page

    Boolean txtPresentOrNot = (driver.getPageSource().contains("Text to check"))

    How do you select a radio button in selenium webdriver

    select = driver.findElements(locator);

    for (WebElement element : select) {if (element.getAttribute("value").equalsIgnoreCase(value)) {

    element.click();

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    5/10

    [email protected]

    }

    }

    Selecting searched dropdown in Selenium-WebDriver

    driver.findElement(locator).click();

    driver.findElement(locator).sendKeys(value);

    driver.findElement(locator).sendKeys(Keys.TAB);

    Clear the textbox typed valuesdriver.findElement(By.id("textbox")).clear();

    To check whether the object is Visible or Invisible

    driver.findElement(By.id("textbox")).isDisplayed();

    To check whether the object is Enabled or Disabled

    driver.findElement(By.id("textbox")).isEnabled();

    How do you verify if the checkbox/radio is checked or not ?

    driver.findElement(By.xpath("xpath of the checkbox/radio button")).isSelected();

    Verify Element Present on the page

    Boolean iselementpresent = driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;

    To get all the links on the webpageList list_1=driver.findElements(By.tagName("a"));

    for (int i = 0; i < list_1.size(); i++) {

    System.out.println(list1.get(i).getText());

    }

    What is partial xpath?

    Description

    Sometimes full xpath is very complex to locate the element

    In such case, we can use the partial xpath using its types as below

    Types

    startsWith

    endsWith

    contains

    Example

    Search

    Assume, Search thing is like below

    Partial Xpath

    //input[endsWith(@name, 'test_this')]

    //input[contains(@name, 'test_this')]

    //input[startsWith(@name, '1473')]

    To get all the links which has a character "r" in the links

    List list1=driver.findElements(By.tagName("a"));

    int j=0;

    for (int i = 0; i < list1.size(); i++) {

    if (list1.get(i).getText().contains("r")) {

    System.out.println("Link Name : "+list1.get(i).getText() + " : "

    + list1.get(i).isDisplayed());

    j++;

    }

    }

    System.out.println("Total Links with r : "+j);Handle Alert Box

    Accept Alert (Click OK on Alert)

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    6/10

    [email protected]

    Alert a = driver.switchTo().alert();

    a.accept();

    Dismiss Alert (Click Cancel on Alert)

    Alert a = driver.switchTo().alert();

    a.dismiss();

    Get the message text of Alert

    Alert a = driver.switchTo().alert();a.getText();

    Enter text in the prompt box (Input on the Alert box)

    Alert a = driver.switchTo().alert();

    a.sendKeys();

    Handling Windows

    Current Window Handle

    String current_handle = driver.getWindowHandle();

    Get All Window Handles

    Set window_handles = driver.getWindowHandles();

    Switch to windowdriver.switchTo().window(handle);

    Switch to each window

    for (String handle:window_handles) {

    driver.switchTo().window(handle);

    }

    Frame Handling

    Switch to Frame

    driver.switchTo().frame(driver.findElements(By.className("demo-frame"));

    driver.switchTo().frame("Frame_id");

    driver.switchTo().frame("frameName.0.child");

    Switch back from frame to main page

    driver.switchTo().defaultContent();

    Example 1

    Web Page

    f1 a b f2

    Description

    Two frames f1 and f2 in web page

    We need to click link "a" in frame "f1"

    then, click link "b" in frame "f2"

    Code

    driver.switchTo.frame("f1");

    driver.findElement(By.linkText("a")).click();

    driver.switchTo.defaultContent();

    driver.switchTo.frame("f2");

    driver.findElement(By.linkText("b")).click();

    driver.switchTo().defaultContent();

    Example 2

    Web Page

    Frame "F1" --> a

    b

  • 7/25/2019 Selenium Material

    7/10

    [email protected]

    Description

    Two frames f1 and f2 in web page

    We need to click link "a" in frame "f1"

    then, click link "b" in frame "f2"

    Codedriver.switchTo.frame("f1");

    driver.switchTo.frame("f2");

    driver.findElement(By.linkText("b")).click();

    driver.switchTo.defaultContent();

    driver.switchTo.frame("f1");

    driver.findElement(By.linkText("a")).click();

    driver.switchTo().defaultContent();

    Snapshot / Screenshot Handling

    Method 1 :

    File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE));FileUtils.copyFile(src, new File("");

    where File is from "java.io" package

    Method 2 :

    EventFiringWebDriver eDriver=new EventFiringWebDriver(driver);

    File srcFile = eDriver.getScreenshotAs(OutputType.FILE);

    FileUtils.copyFile(srcFile, new File(imgPath));

    How to check all checkboxes in a page?

    List chkBox = driver.findElements(By.xpath("//htmltag[@attbute]"));

    for(int i=0; i

  • 7/25/2019 Selenium Material

    8/10

    [email protected]

    Try to open the the firefox browser with the above created firefox profile.

    Program 1

    FirefoxProfile profile = new FirefoxProfile();

    profile.setAcceptUntrustedCertificates(false);

    profile.setAssumeUntrustedCertificateIssuer(false);

    WebDriver driver = new FirefoxDriver(profile);

    driver.get("url");How do you manage proxies in browser?

    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("network.proxy.type", 1);

    profile.setPreference("network.proxy.http", "proxy-url.com");

    profile.setPreference("network.proxy.http_port", 80);

    profile.setPreference("network.proxy.ssl", "proxy-url.com");

    profile.setPreference("network.proxy.ssl_port", 80);

    profile.setPreference("network.proxy.ftp", "proxy-url.com");

    profile.setPreference("network.proxy.ftp_port", 80);

    profile.setPreference("network.proxy.socks", "proxy-url.com");profile.setPreference("network.proxy.socks_port", 80);

    FirefoxDriver fire_driver=new FirefoxDriver(profile);

    How will you work with DataProviders?

    Description

    When you need to pass complex parameters or parameters that need to be

    created from Java

    In such cases parameters can be passed using Dataproviders

    A Data Provider is a method annotated with @DataProvider

    A Data Provider returns an array of objects

    Create a name for the dataprovider and give it in its annotation

    And assign the name to dataProvider at @test method

    Notes

    In the below examples, 4 different values are passed

    So the @Test method will run 4 times with 4 different values

    Example

    @DataProvider(name = "Search")

    public static Object[][] credentials() {

    return new Object[][] { { "manikandan vb"}, { "9994946924"}, {"1212.in"},

    {"Selenium"}, {"9791039962"}};

    }

    @Test(dataProvider = "Search")

    public void f(String word) {

    WebDriver driver=new FirefoxDriver();

    driver.manage().window().maximize();

    driv

    driver.findElement(By.id("gbqfq")).sendKeys(word);

    System.out.println("Now Searching for : "+word);

    driver.close();

    }

    Reading ToolTip text in in Selenium-WebDriver

    public static String tooltipText(WebDriver driver, By locator){String tooltip = driver.findElement(locator).getAttribute("title");

    return tooltip;

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    9/10

    [email protected]

    }

    Deleting all Cookies before doing any kind of action

    driver.manage().deleteAllCookies();

    How can we get the font size, font color, font type used for a particular text on a web page

    using Selenium web driver

    driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size);

    driver.findelement(By.Xpath("Xpath ").getcssvalue("font-colour);driver.findelement(By.Xpath("Xpath ").getcssvalue("font-type);

    driver.findelement(By.Xpath("Xpath ").getcssvalue("background-colour);

    How to get the number of frames on a page ?

    List framesList = driver.findElements(By.xpath("//iframe"));

    int numOfFrames = frameList.size();

    What is the use of getOptions() method ?

    getOptions() is used to get the selected option from the dropdown list

    Which is the super interface of webdriver ?

    SearchContext

    ProfileSet Proxy profile for Socks HTTP

    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("network.proxy.type", 1);

    profile.setPreference("network.proxy.socks", "localhost");

    profile.setPreference("network.proxy.socks_port", 7555);

    FirefoxDriver driver = new FirefoxDriver(profile);

    Set Proxy profile for Socks HTTP

    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("network.proxy.http", "localhost");

    profile.setPreference("network.proxy.http_port", "3128");

    WebDriver driver = new FirefoxDriver(profile);

    Tweaking an existing Firefox profile

    Method 1

    ProfilesIni allProfiles = new ProfilesIni();

    FirefoxProfile profile = allProfiles.getProfile("WebDriver");

    profile.setPreferences("foo.bar", 23);

    WebDriver driver = new FirefoxDriver(profile);

    Alternatively, if the profile isn't already registered with Firefox

    File profileDir = new File("path/to/top/level/of/profile");

    FirefoxProfile profile = new FirefoxProfile(profileDir);

    profile.setPreferences(extraPrefs);

    WebDriver driver = new FirefoxDriver(profile);

    Enabling features that are disabled by default in Firefox

    FirefoxProfile profile = new FirefoxProfile();

    profile.setEnableNativeEvents(true);

    WebDriver driver = new FirefoxDriver(profile);

    How to set language in profile

    profile.setPreference( "intl.accept_languages", "no,en-us,en" );

    Changing the user agent

    FirefoxProfile profile = new FirefoxProfile();

    profile.setPreference("general.useragent.override", "some UA string");WebDriver driver = new FirefoxDriver(profile);

    Firefox Configuration Settings - To overcome Proxy authentication prompt

    [email protected]

    9791039962

  • 7/25/2019 Selenium Material

    10/10

    [email protected]

    Description

    This works fine without prompting any authentication when you do the

    following settings

    Steps

    Type "about:config" on your FF url

    Now type "Proxy" in the search field

    Make sure "signon.autologin.proxy" is set "true" (By default it is "false")Cookies

    Add a Cookie

    driver.manage().addCookie(cookieName cookieValue);

    Get a Cookie Name & Cookie Value

    Set cookies=driver.manage().getCookies();

    System.out.println(cookie.getName()+" "+cookie.getValue());

    Get the domain name

    System.out.println("Cookie Domain : "+cookie.getDomain());

    Get the Path

    System.out.println("Cookie Path : "+cookie.getPath());Get the Expiry time of Cookie

    System.out.println("Cookie Expiry : "+cookie.getExpiry());

    To check it is only for HTTp

    System.out.println("Cookie HTTP : "+cookie.isHttpOnly());

    To check it is secured

    System.out.println("Cookie Secure : "+cookie.isSecure());

    Delete cookies by Name

    driver.manage().deleteCookieNamed(cookie.getName());

    Delete cookies directly

    driver.manage().deleteCookie(cookie);

    Delete All cookies

    driver.manage().deleteAllCookies();

    Program

    driver.get("http://in.yahoo.com/");

    Set cookies=driver.manage().getCookies();

    System.out.println("Number of cookies in this site "+cookies.size());

    driver.manage().addCookie("cookieName" "cookieValue");

    for(Cookie cookie:cookies) {

    System.out.println(cookie.getName()+" "+cookie.getValue());

    driver.manage().deleteCookieNamed(cookie.getName());

    driver.manage().deleteCookie(cookie);

    }

    driver.manage().deleteAllCookies();

    [email protected]

    9791039962