Showing posts with label selenium. Show all posts
Showing posts with label selenium. Show all posts

Monday, October 17, 2016

XPath Selectors.

driver.findElement(By.xpath(“ // ...”));
element.findElement(By.xpath(“ // ...”));
element.findElement(By.xpath(“. // ...”));

By Index
  • //td[text()='Books']
  • (//li)[1]
  • (//li)[last()]
  • (//li)[1]/..
  • (//li)[last()]/..
  • //nodename[3] - 3rd child of its parent node
  • (//nodename)[3] - 3rd nodename element

Xpath Axes
  • AxisName::nodetest[predicate]
  • ex. //td[text()='Books']/ancestor::table
  • AxisName
    • ancestor
    • ancestor-or-self
    • descendant
    • descendant-or-self
    • following
    • following-sibling
    • preceding
    • preceding-sibling
    • parent
    • child
    • self
driver.findElement(By.xpath("//td[text()='Books']/ancestor::table"));

// driver.findElement(By.xpath(“//...”)); 
// element.findElement(By.xpath(“//...”)); 
// element.findElement(By.xpath(“.//...”));

// Notice the difference
//
// <div id="id0">
//        <p>Hello</p>
// </div>
// <div id="id1">
//        <p>World</p>
// </div>

// current node is "driver"
driver.findElement(By.id("id1"))
        .findElement(By.xpath("//p")).getText()  //=> Hello  
driver.findElement(By.id(“id1”))
        .findElement(By.xpath(".//p")).getText() //=> World


Selenium 101.

Basics
  • driver.findElements(...).findElement(...)

By ID
  • Java: driver.findElement(By.id(...)) 
  • Python: driver.find_element_by_id(...)
WebElement id1 = driver.findElement(By.id("id1"));

// Can combine with Xpath searching
id1.findElement(By.xpath("/p"));

By Name
  • Java: driver.findElement(By.name(...))
  • Python: driver.find_element_by_name(...)
@Test
public void findElementByName() {
        WebElement input =
           driver.findElement(By.name("keyword"));
        assertEquals("Type in your keyword",
           input.getAttribute("value"));
}
By ClassName
  • Java: driver.findElement(By.className(...))
  • Python: driver.find_element_by_class_name(...)
@Test
public void findElementByClassName() {
        WebElement label =
           driver.findElement(By.className("label"));
        assertEquals("Search", label.getText());
}
By TagName
  • Java: driver.findElement(By.tagName(...))
  • Python: driver.find_element_by_tag_name(...)
@Test
public void findLisInsideUl() {
        WebElement ul =
           driver.findElement(By.id("list2"));
        List lis =
           ul.findElements(By.tagName("li"));
        assertEquals(3, lis.size());
        List lis2 =
           driver.findElements(By.tagName("li"));
        assertEquals(8, lis2.size());
}
By Links
  • Java: driver.findElement(By.linkText(...))
  • Python: driver.find_element_by_link_text(...)
  • Java: driver.findElement(By.partialLinkText(...))
  • Python: driver.find_element_by_partial_link_text(...)
@Test
public void testFindLinkByText() {
        WebElement link =
           driver.findElement(By.linkText("Facebook"));
        String url = link.getAttribute("href");
        assertEquals("https://www.facebook.com/", url);
}

@Test
public void testFindLinkByPartialText() {
        WebElement link =
           driver.findElement(By.partialLinkText("Digg"));
        String url = link.getAttribute("href");
        assertEquals("http://www.digg.com/", url);
}
By XPATH
  • Java: driver.findElement(By.xpath("nodename..."))
  • Python: driver.find_element_by_xpath("nodename...")
  • nodename:
    • /     - root element
    • //    - current element/node
    • .     - current node
    • ..    - parent of current node
    • @  - an attribute
    • [ ]  - predicate
By.xpath(“//form[@name=‘site-search']// input[@type='submit']")
By.xpath(“//form[@name=‘site-search']/ input[@type='submit']")

/****************************
* useful xpath expressions
*****************************/
//input[@id], //img[@alt], //img[not(@alt)]
//input[@id=‘username’]
//input[@type=‘submit’ and @value=‘login’]
//input[@type=‘submit’][@value=‘login’]
//input[@type=‘submit’ or @value=‘login’]
//input[starts-with(@name, ‘username’)]
//input[contains(@id, ‘name’)]
//input[ends-with(@id, ‘name’)]

WebElement p2 = id1.findElement(By.xpath("./p"));
assertEquals("World", p2.getText());
WebElement p3 = id1.findElement(By.xpath("//p"));
assertEquals("Hello", p3.getText());
WebElement p4 = id1.findElement(By.xpath(".//p"));
assertEquals("World", p4.getText());

@Test
public void findUl() {
        WebElement list =
           driver.findElement(By.xpath("//ul"));
        assertEquals("list1", list.getAttribute("id"));
}

@Test
public void findLis() {
        List lis =
           driver.findElements(By.xpath("//li"));
        assertEquals(8, lis.size());
        List lis2 =
           driver.findElements(By.xpath("//ul/li"));
        assertEquals(7, lis2.size());
        List lis3 =
           driver.findElements(By.xpath("//ul//li"));
        assertEquals(8, lis3.size());
}

@Test
public void findLinksWithTargetAttribute() {
        List links =
           driver.findElements(By.xpath("//*[@target]"));
        assertEquals(2, links.size());

        String[] expectedUrls =
           new String[] {
                               "https://www.google.com/",
                               "http://www.msn.com/"
           };
        List actualUrls = new ArrayList();

        for (WebElement link : links) {
           actualUrls.add(link.getAttribute("href"));
        }

        assertArrayEquals(expectedUrls,
           actualUrls.toArray());
}

@Test
public void findLinkThatOpenNewTab() {
        WebElement link =
           driver.findElement(By.xpath("//a[@target='_blank']"));
        assertEquals("MSN Link", link.getText());
}

@Test
public void findAllSecureLinks() {
        List links =
           driver.findElements(
              By.xpath("//ul[@id='list2']//a[starts-with(@href, 'https')]")
                );
        System.out.println("Secure links:");
        for (WebElement link : links) {
           System.out.println(link.getAttribute("href"));
        }
}

@Test
public void findAllPDFLinks() {
        List links =
           driver.findElements(
              By.xpath("//ul[@id='list2']//a[ends-with(@href, 'pdf')]")
                );
        System.out.println("PDF links:");
        for (WebElement link : links) {
           System.out.println(link.getAttribute("href"));
        }
}

CSS
  • Java: driver.findElement(By.cssSelector(...))
  • Python: driver.find_element_by_css_selector(...)
  • Tag selector         : By.cssSelector("input")
  • Class selector      : By.cssSelector(".login")
  • ID selector           : By.cssSelector("#title")
  • Attribute selector (can be full or partial match)
    • a[href^="https"]       - starts with
    • a[href$=".pdf"]        - ends with
    • a[href*="google"]    - contains

Example
  • Find child elements from parent elements
    • By.cssSelector("tbody > tr:nth-child(3)”)
    • form > label:last-child vs. label:last-of-type
  • Find sibling elements
    • form > input[name^='username'] + * + label
  • Find elements based on various states
    • :enabled, :disabled, :checked, :focus, :hover, :active
    • By.cssSelector(“input[type='checkbox']:not(:checked)")
  • CSS selectors

WebElement ele1 = driver.findElement(By.cssSelector(".primary-btn"));
WebElement ele2 = driver.findElement(By.cssSelector("btn.primary-btn"));
WebElement ele3 = driver.findElement(By.cssSelector("btn.primary-btn"));

WebElement Email = driver.findElement(By.cssSelector("input[id=email]"));
Email.SendKeys("hello@sampleemail.com");


Interactive Elements

Selenium Jump Start.

Step 1. Download Tools

Step 2. Start a Java Project From Eclipse
  • Right click the project and go to the bottom to open "properties.
  • Choose Libraries and add external JARs
  • Copy your executable chromedriver to Java Project folder
    • In the following example, we put it under "./drivers"
    • In MAC, you need to manually "chmod +x" or "chmod 755"
    • In PC, the file name has ".exe" suffix
  • Go to the "src" folder, right click to add new class
  • Insert the following codes
  • When you run, run as JUnit Test.
package com.yourdomain.topfolder.subfolder;
import java.util.List;
import ...

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class myDemo {

        private WebDriver driver;

        @Before
        public void setUp() {
                System.setProperty("webdriver.chrome.driver",
                                "./drivers/chromedriver.exe");

                driver = new ChromeDriver(); // launch the browser
                driver.get("http://www.ebay.com");
        }

        @After
        public void tearDown() {
                driver.quit(); // close the browser
        }

        @Test
        public void testById() {
           ...
        }
}


Step 3. Use Inspect to find elements for testing
WebElement elem = driver.findElement(By.id("title"));
assertEquals("Hello World", elem.getText());

List elems = driver.findElements(By.tagName("h1"));
assertEquals("Hello World", elems.get(0).getText());

// Pay attention to which page you are
// In home page
WebElement input = driver.findElement(By.id("twotabsearchtextbox"));
input.clear();
input.sendKeys("selenium webdriver books");
WebElement searchIcon = driver.findElement(By.className("nav-input"));
searchIcon.click();

WebElement searchButton = 
        driver.findElement(By.xpath(
            “/html/body/div[2]/header/div/div[1]/div[3]/
              div/form/div[2]/div/ input”));
searchButtom.click();
System.out.println(driver.findElement(By.id("s-result-count")).getText());

// Now I am in the result page!
WebElement status = driver.findElement(By.id("s-result-count"));
System.out.println(status.getText());
assertEquals( 
        "1-16 of 65 results for \"selenium webdriver books\"",
        status.getText()
);