Example usage for org.openqa.selenium By xpath

List of usage examples for org.openqa.selenium By xpath

Introduction

In this page you can find the example usage for org.openqa.selenium By xpath.

Prototype

public static By xpath(String xpathExpression) 

Source Link

Usage

From source file:ca.nrc.cadc.search.integration.AbstractSearchFormPage.java

License:Open Source License

void closeTooltip() throws Exception {
    final By tooltipCloseLink = By.xpath("//*[contains(@class, 'glyphicon-remove-circle')]");
    waitForElementPresent(tooltipCloseLink);
    final WebElement tooltipClose = find(tooltipCloseLink);
    click(tooltipClose);/*from w  w  w .j av  a 2 s  .co  m*/
}

From source file:ca.pe.cjsigouin.testinator.selenium.WebDriverMain.java

public static void main(String[] args) {

    System.setProperty("webdriver.gecko.driver", "/home/krystofurr/Programs/selenium/geckodriver");
    System.setProperty("webdriver.chrome.driver", "/home/krystofurr/Programs/selenium/chromedriver");

    //     WebDriver driver = new FirefoxDriver();
    WebDriver driver = new ChromeDriver();
    //     WebDriver driver = new InternetExplorerDriver();

    //Puts an Implicit wait, Will wait for 10 seconds before throwing exception
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    //Launch website
    driver.navigate().to(CommonConstants.HOST + CommonConstants.URL_LOGIN);

    driver.findElement(By.id("emailAddress")).sendKeys("cjsigouin@gov.pe.ca");
    driver.findElement(By.id("password")).sendKeys("Test12345!");
    driver.findElement(By.id("loginButton")).click();

    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(/*ww  w .j a va  2  s  .com*/
            ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='serviceWellSection']/div[2]/div/a/b")));

    driver.get(CommonConstants.HOST + CommonConstants.URL_RESERVE_NAME_INTRO);
    WebDriverWait wait2 = new WebDriverWait(driver, 5);

    wait2.until(ExpectedConditions.elementToBeClickable(By.xpath(ReserveNameElement.INTRO_BUTTON_CANCEL)));
    driver.findElement(By.xpath(ReserveNameElement.INTRO_RADIO_RESERVE_NAME)).click();
    //     driver.findElement(By.xpath(ReserveNameElement.INTRO_SELECT_COMPANY_TYPE)).sendKeys("Incorp");

    Select dropdown = new Select(driver.findElement(By.xpath(ReserveNameElement.INTRO_SELECT_COMPANY_TYPE)));
    dropdown.selectByVisibleText("Incorporated");
    driver.findElement(By.xpath(ReserveNameElement.INTRO_BUTTON_NEXT)).click();

    //     WebDriver driver = new FirefoxDriver();
    //     LoginTester login = new LoginTester(driver);
    //     IncorporatedTester tester = new IncorporatedTester(driver);
    //
    //     login.start();

    //     //Maximize the browser
    //     driver.manage().window().maximize();
    //     tester.start();
    //     tester.stop();

    //     // Click on Math Calculators
    //     driver.findElement(By.xpath(".//*[@id='hcalc']/table/tbody/tr/td[2]/div[3]/a")).click();
    //     
    //     // Click on Percent Calculators
    //     driver.findElement(By.xpath(".//*[@id='content']/ul[1]/li[3]/a")).click();
    //     
    //     // Enter value 10 in the first number of the percent Calculator
    //     driver.findElement(By.id("cpar1")).sendKeys(data.getNumberText(2));
    //     
    //     // Enter value 50 in the second number of the percent Calculator
    //     driver.findElement(By.id("cpar2")).sendKeys(data.getNumberText(2));
    //     
    //     // Click Calculate Button
    //     driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/tr[2]/td/input[2]")).click();
    //   
    //     
    //     // Get the Result Text based on its xpath
    //     String result = driver.findElement(By.xpath(".//*[@id='content']/p[2]/font/b")).getText();
    //   
    //     
    //     // Print a Log In message to the screen
    //     System.out.println(" The Result is " + result);

    //Close the Browser.
    driver.close();
}

From source file:calc.CalculatorUIT.java

public void testCodesCrud(DesiredCapabilities browser) throws Exception {

    ExtentReports logger = new ExtentReports("target//advancedReport.html", false);
    ExtentTest test1 = logger.startTest("Verify Target String");
    ExtentTest test2 = logger.startTest("Verify Calculation Result");

    WebDriver driver = null;/* w w w  .  j a v a 2 s  . c o m*/
    System.out.println("Attempt connect to Selenium Node @ " + NodeURL);
    File pathToBinary = new File("/opt/firefox46/firefox/firefox-bin");
    FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
    FirefoxProfile firefoxProfile = new FirefoxProfile();
    driver = new FirefoxDriver(ffBinary, firefoxProfile);
    try {
        System.out.println("attempt connect to target: " + TargetURL);
        driver.get(TargetURL);
        //input a addition 12+8 example in the calculator web-application;
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[2]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[3]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[12]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[10]")).click();
        driver.findElement(By.xpath("(//input[@id='buttonRow'])[15]")).click();

        //search target string value
        String targetStr = "Welcome to the Demo";

        //verify result
        boolean isFound = (driver.findElement(By.tagName("body")).getText()).contains(targetStr);
        boolean result = driver.findElement(By.name("display")).getAttribute("value").contains("84");

        //verify title  
        if (isFound == true) {
            test1.log(LogStatus.PASS, "Title has been verified");
        }
        if (isFound == false) {
            test1.log(LogStatus.FAIL, "Title has NOT been verified");
        }

        //verify result     
        if (result == true) {
            test2.log(LogStatus.PASS,
                    "The Calculation result was correct: [12 multiply by 7 gave output of 84]");
        } else {
            test2.log(LogStatus.FAIL,
                    "The Calculation result was not correct [the title is[Welcome to the Demo!]");

        }
        logger.endTest(test1);
        logger.endTest(test2);
        logger.flush();

        System.out.println("look for= [" + targetStr + "]");
        System.out.println("did we find it? [" + isFound + "]");

        System.out.println("calculate 12 multiply by 7");
        System.out.println("Was the result 84 ? [" + result + "]");

        Assert.assertTrue(isFound);
        Assert.assertTrue(result);
        //  Assert.assertEquals("hell",driver.getTitle());
        //doTest(driver); 
        // rest of test commands come here
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(e.getMessage(), false);
    } finally {
        if (driver != null) {
            driver.quit();
        }
    }
}

From source file:CartTest.CartTest.java

@Test
public void addToCart() {

    //There are two kinds of Categories to show products. Therefore, I should consider two situations.
    String name;//from  www  .java 2s.  c o m
    WebElement addtocart = driver.findElement(By
            .xpath("//*[@id=\"default_products_page_container\"]/div[3]/div[2]/form/div[2]/div[1]/span/input"));
    if (addtocart == null) {
        addtocart = driver.findElement(By.xpath(
                "//*[@id=\"grid_view_products_page_container\"]/div[3]/div[1]/div[3]/form/div/div[1]/span/input"));
        name = driver
                .findElement(
                        By.xpath("//*[@id=\"grid_view_products_page_container\"]/div[3]/div[1]/div[2]/h2/a"))
                .getText();
    } else {
        name = driver.findElement(By.xpath("//*[@id=\"default_products_page_container\"]/div[3]/div[2]/h2/a"))
                .getText();
        System.out.println(name);
    }

    addtocart.click();

    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);// wait for web response
    driver.findElement(By.xpath("//*[@id=\"fancy_notification_content\"]/a[1]")).click();// click "go to checkout" button
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);//wait

    String itemName = driver
            .findElement(By.xpath("//*[@id=\"checkout_page_container\"]/div[1]/table/tbody/tr[2]/td[2]/a"))
            .getAttribute("text");
    System.out.println("xxx" + itemName);
    String quantity = driver
            .findElement(By
                    .xpath("//*[@id=\"checkout_page_container\"]/div[1]/table/tbody/tr[2]/td[3]/form/input[1]"))
            .getAttribute("value");

    assertEquals(quantity, "1");// the quantity should be one;
    assertEquals(itemName, name);// the item should be what I added
}

From source file:CartTest.CartTest.java

@Test
public void changeQuantity() {

    this.addItemIntoCart();

    WebElement itemQuantity = driver.findElement(
            By.xpath("//*[@id=\"checkout_page_container\"]/div[1]/table/tbody/tr[2]/td[3]/form/input[1]"));
    itemQuantity.clear();//clear the quantity input bar
    itemQuantity.sendKeys("10");//change the quantity into 10
    driver.findElement(/* ww  w . java  2 s  .c  o  m*/
            By.xpath("//*[@id=\"checkout_page_container\"]/div[1]/table/tbody/tr[2]/td[3]/form/input[4]"))
            .click();//press "change" button
    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);// wait
    assertEquals(driver
            .findElement(
                    By.xpath("//*[@id=\"checkout_page_container\"]/div[1]/table/tbody/tr[2]/td[5]/span/span"))
            .getText(), "$120.00");// the total price should become to "120"

}

From source file:CartTest.CartTest.java

@Test
public void testRemove() {
    this.addItemIntoCart();
    driver.findElement(//w w w.  ja va  2  s .  c o m
            By.xpath("//*[@id='checkout_page_container']/div[1]/table/tbody/tr[2]/td[6]/form/input[4]"))
            .click();//*[@id="checkout_page_container"]/div[1]/table/tbody/tr[2]/td[6]/form/input[4]
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
    WebElement content = driver.findElement(By.xpath("//*[@id=\"post-29\"]/div"));//find empty cart notification
    assertEquals(content.getText(), "Oops, there is nothing in your cart.");// The cart should be empty
}

From source file:CartTest.CartTest.java

private void addItemIntoCart() {
    WebElement addtocart = driver.findElement(By
            .xpath("//*[@id=\"default_products_page_container\"]/div[3]/div[2]/form/div[2]/div[1]/span/input"));
    if (addtocart == null) {
        addtocart = driver.findElement(By.xpath(
                "//*[@id=\"grid_view_products_page_container\"]/div[3]/div[1]/div[3]/form/div/div[1]/span/input"));
    }/*from w  w w . ja v a 2 s  .c  o  m*/

    addtocart.click();

    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);// wait for web response
    driver.findElement(By.xpath("//*[@id=\"fancy_notification_content\"]/a[1]")).click();// click "go to checkout" button
    driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);//wait
}

From source file:cc.gospy.example.zhihu.ZhihuUserSpider.java

License:Apache License

public static void main(String[] args) {
    String startUrl = "selenium://https://www.zhihu.com/people/giantchen/following?page=1";
    String chromeDriverPath = "D:/Program Files/Chrome Driver/chromedriver.exe";

    // a demo of using selenium
    Gospy.custom()//from   w ww. jav  a2 s  . c  om
            .setScheduler(Schedulers.VerifiableScheduler.custom().setPendingTimeInSeconds(300)
                    .setAutoExit(false).build())
            .addFetcher(Fetchers.TransparentFetcher.custom().convertHttpTaskToSelenium().build())
            .addProcessor(Processors.SeleniumProcessor.custom().setDriver(Browser.Chrome, chromeDriverPath)
                    .setWebDriverExecutor((page, driver) -> {
                        Collection<Task> newTasks = new HashSet<>();
                        boolean visited = false;
                        while (!visited) {
                            try {
                                WebElement nextPageButton = driver
                                        .findElement(By.className("PaginationButton-next"));
                                while (nextPageButton.isDisplayed()) {
                                    nextPageButton.click();
                                    while (true) {
                                        Thread.sleep(1000);
                                        try {
                                            if (driver.findElement(By.className("UserLink-link")).isEnabled()) {
                                                visited = true;
                                                break;
                                            }
                                        } catch (Exception e) {
                                        }
                                    }
                                    Thread.sleep(1000);
                                    List<WebElement> elements = driver.findElements(By.xpath(
                                            "//*[@id='Profile-following']/div[2]/div/div/div/div[2]/h2/div/span/div/div/a"));
                                    elements.forEach(e -> {
                                        Task newTask = new Task("selenium://"
                                                + e.getAttribute("href").concat("/following?page=1"));
                                        newTask.setDepth(page.getTask().getDepth() + 1);
                                        System.out
                                                .println("find " + e.getText() + "\t" + e.getAttribute("href"));
                                        newTasks.add(newTask);
                                    });
                                }
                            } catch (Exception e) {
                            }
                        }
                        User user = new User();
                        user.setDistance(page.getTask().getDepth());
                        user.setUsername(driver.findElement(By.className("ProfileHeader-name")).getText());
                        WebElement detailButton;
                        try {
                            detailButton = driver.findElement(
                                    By.xpath("//*[@id='ProfileHeader']/div/div[2]/div/div[2]/div[3]/button"));
                            detailButton.click();
                        } catch (NoSuchElementException e) {
                            return new Result<>(newTasks, user);
                        }
                        while (!driver.findElement(By.className("ProfileHeader-detail")).isDisplayed())
                            ;
                        for (WebElement e : driver.findElements(By.xpath(
                                "//*[@id='ProfileHeader']/div/div[2]/div/div[2]/div[2]/span/div/div/span"))) {
                            switch (e.getText().trim()) {
                            case "?":
                                user.setResidence(e.findElement(By.xpath("./../div/span")).getText());
                                break;
                            case "":
                                user.setIndustry(e.findElement(By.xpath("./../div")).getText());
                                break;
                            case "??":
                                StringBuffer buffer = new StringBuffer();
                                e.findElements(By.xpath("./../div/div")).forEach(webElement -> {
                                    buffer.append(webElement.getText()).append("\t");
                                });
                                user.setJobs(buffer.toString());
                                break;
                            case "?":
                                buffer = new StringBuffer();
                                e.findElements(By.xpath("./../div/div")).forEach(webElement -> {
                                    buffer.append(webElement.getText()).append("\t");
                                });
                                user.setEducations(
                                        buffer.length() > 1 ? buffer.substring(0, buffer.length() - 1) : null);
                                break;
                            case "":
                                user.setIntro(
                                        e.findElement(By.xpath("./../div")).getText().replaceAll("\n", " "));
                                break;
                            default:
                                System.err.println("unknown detail [" + e.getText() + "]");
                            }
                        }
                        return new Result<>(newTasks, user);
                    }).setTaskFilter(TaskFilter.SELENIUM).build())
            .setExceptionHandler((throwable, task, page) -> {
                if (throwable.getCause() != null
                        && (throwable.getCause().getClass() == NoSuchWindowException.class
                                || throwable.getCause().getClass() == WebDriverException.class)) {
                    System.out.println("Browser is closed, exit now!");
                    System.exit(0);
                }
                throwable.printStackTrace();
                if (task != null) {
                    if (!task.getUrl().startsWith("selenium://")) {
                        task.setUrl("selenium://".concat(task.getUrl()));
                        System.err.println("Retry " + task);
                        return Arrays.asList(task);
                    }
                }
                return null;
            }).addPipeline(Pipelines.ConsolePipeline.getDefault()).build().addTask(new Task(startUrl)).start();
}

From source file:cc.kune.selenium.spaces.UserSpacePageObject.java

License:GNU Affero Public License

/**
 * Gets the first wave.
 * 
 * @return the first wave
 */
public WebElement getFirstWave() {
    return findElement(By.xpath("//div[3]/div/div/span"));
}

From source file:cc.kune.selenium.spaces.UserSpacePageObject.java

License:GNU Affero Public License

/**
 * Gets the new wave.
 * 
 * @return the new wave
 */
public WebElement getNewWave() {
    return findElement(By.xpath("//div[2]/div[2]/div[4]"));
}