Example usage for org.openqa.selenium WebElement click

List of usage examples for org.openqa.selenium WebElement click

Introduction

In this page you can find the example usage for org.openqa.selenium WebElement click.

Prototype

void click();

Source Link

Document

Click this element.

Usage

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()/* w w  w .j a v a 2s .c o  m*/
            .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:ccnu.computer.crawler.WeiboCN.java

/**
 * ??cookieweibo.cnweibo.com weibo.cn?????
 *
 * @param username ???//  www .ja  v  a  2s .co m
 * @param password ??
 * @return
 * @throws Exception
 */
public static String getSinaCookie(String username, String password) throws Exception {
    StringBuilder sb = new StringBuilder();
    HtmlUnitDriver driver = new HtmlUnitDriver();
    driver.setJavascriptEnabled(true);
    driver.get("http://login.weibo.cn/login/");
    WebElement ele = driver.findElementByCssSelector("img");
    String src = ele.getAttribute("src");
    String cookie = concatCookie(driver);
    HttpRequest request = new HttpRequest(src);
    request.setCookie(cookie);
    HttpResponse response = request.getResponse();
    ByteArrayInputStream is = new ByteArrayInputStream(response.getContent());
    BufferedImage img = ImageIO.read(is);
    is.close();
    ImageIO.write(img, "png", new File("result.png"));
    String userInput = new CaptchaFrame(img).getUserInput();
    WebElement mobile = driver.findElementByCssSelector("input[name=mobile]");
    mobile.sendKeys(username);
    WebElement pass = driver.findElementByCssSelector("input[name^=password]");
    pass.sendKeys(password);
    WebElement code = driver.findElementByCssSelector("input[name=code]");
    code.sendKeys(userInput);
    WebElement rem = driver.findElementByCssSelector("input[name=remember]");
    rem.click();
    WebElement submit = driver.findElementByCssSelector("input[name=submit]");
    submit.click();
    String result = concatCookie(driver);
    driver.close();
    if (result.contains("gsid_CTandWM")) {
        return result;
    } else {
        throw new Exception("weibo login failed");
    }
}

From source file:chromedriveryahoologin.ChromeDriverDeleteTrashEmails.java

public static void main(String[] args) {
    try {//from   w  w w  .j a v a2  s . c  om

        Integer pozSpam = 0;
        Integer pozTrash = 0;
        Integer pozHelp = 0;
        Integer pozCompose = 0;
        Integer pozNewFolder = 0;

        System.setProperty("webdriver.chrome.driver",
                "D:\\Proiecte\\selenium-java-2.47.1\\selenium-2.47.1\\chromedriver_win32\\chromedriver.exe");
        System.setProperty("webdriver.chrome.logfile",
                "D:\\prjAutJava\\YahooLogin\\ChromeDriverDeleteSpam.log");
        ChromeOptions options = new ChromeOptions();
        options.addArguments("test-type");
        options.addArguments("--start-maximized");
        options.addArguments("--disable-web-security");
        options.addArguments("--no-proxy-server");
        options.addArguments("--disable-extensions");
        options.addArguments("--disable-notifications");
        options.addArguments("--disable-popup-blocking");
        options.addArguments("--disable-plug-in");
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("credentials_enable_service", false);
        prefs.put("profile.password_manager_enabled", false);

        options.setExperimentalOption("prefs", prefs);

        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);
        capabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, true);
        capabilities.setCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, true);
        capabilities.setCapability(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);
        capabilities.setCapability(CapabilityType.SUPPORTS_ALERTS, true);
        capabilities.setCapability(CapabilityType.PLATFORM, "WIN10");

        driver = new ChromeDriver(capabilities);
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("https://mail.yahoo.com");
        driver.manage().window().maximize();
        WebElement usernameElem = driver.findElement(By.id("login-username"));
        usernameElem.sendKeys("andadeacu@yahoo.com");

        WebElement Next = driver.findElement(By.name("signin"));
        Next.click();

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

        WebElement passwordElem = driver.findElement(By.xpath("//input[@id='login-passwd']"));
        boolean selected = passwordElem.isSelected();

        CharSequence password = "";
        passwordElem.sendKeys(password);

        WebElement login = driver.findElement(By.id("login-signin"));

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

        driver.switchTo().activeElement();

        WebElement tooltipElem = driver.findElement(By.xpath("//div[@class='Pos(r) M(0) TooltipContent']"));

        List<WebElement> childs = tooltipElem.findElements(By.xpath("//ul/li"));

        for (int j = 0; j < childs.size(); j++) {

            WebElement spamElem = childs.get(j);
            /*
            * System.out.println("ancorele " + j + " " + " tag " +
            * childs.get(j).getTagName() + " " + childs.get(j).getText() +
            * " " + childs.get(j).getAttribute("innerHTML"));
             */
            if (spamElem.getText().startsWith(("Spam"))) {

                pozSpam = j;

            }
            if (spamElem.getText().startsWith(("Help"))) {

                pozHelp = j;

            }
            if (spamElem.getText().startsWith(("Compose"))) {

                pozCompose = j;

            }
            if (spamElem.getText().startsWith(("New"))) {

                pozNewFolder = j;

            }

            if (spamElem.getText().startsWith(("Trash"))) {
                System.out.println(j + " Trash is " + spamElem.getTagName() + " " + spamElem.getText());
                pozTrash = j;
                break;
            }

        }
        System.out.println(pozTrash);

        WebElement trashElem = childs.get(pozTrash);

        /*
        * System.out.println("trashElem " + trashElem.getTagName() +
        * " text " + trashElem.getText() + " class_atribute " +
        * trashElem.getAttribute("class") + " data_action " +
        * trashElem.getAttribute("data_action"));
         */
        WebElement trashFolderEmpty = trashElem.findElement(
                By.xpath("//a[@class='x-gap btn btn-trash']/span/span[@class='btn icon  icon-delete']"));

        /*
        * System.out.println("spamEmptyFolder " +
        * spamFolderEmpty.getTagName() + " text " +
        * spamFolderEmpty.getText() + " location " +
        * spamFolderEmpty.isEnabled());
         */
        trashFolderEmpty.click();

        int timeOut = 5;

        WebDriverWait wait = new WebDriverWait(driver, timeOut);

        driver.switchTo().alert();

        /* for Chrome is not working 
        WebElement modalPopUp = driver.findElement(By
            .className("modal-hd yui3-widget-hd"));
                
        */

        WebElement btnDeleteSpamEmails = driver.findElement(By.className("btn left right default"));

        /*
        * <button id="okayModalOverlay" class="btn left right default"
        * title="OK" role="button" data-action="ok">OK</button>
         */
        btnDeleteSpamEmails.click();

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

        driver.switchTo().activeElement();

        // verify msg after you delete spam emails
        System.out.println(driver.getCurrentUrl());

        driver.quit();
    } catch (Exception ex) {

        ex.printStackTrace();
        driver.quit();
    }

}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void clickGetInfo() throws Throwable {
    WebElement getInfoBtn = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[1]/div[2]/div/button"));
    getInfoBtn.click();
}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void selectDiscount(String isDiscount) throws Throwable {
    WebElement discount = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[3]/div[3]/div/label[1]/input"));
    WebElement unDiscount = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[3]/div[3]/div/label[2]/input"));
    if (isDiscount.equalsIgnoreCase("true") == true) {
        discount.click();
    } else {/*from  w w w.j a  va2 s . co  m*/
        unDiscount.click();
    }
}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void uploadBusinessLicense() throws Throwable {
    WebElement businessLicenseBtn = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[11]/div/div/button[1]"));
    businessLicenseBtn.click();
    Thread.sleep(1000);//from w  w  w . j a  v  a  2 s. c  o m
    uploadFileAfterClick();
}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void uploadBusinessPlace() throws Throwable {
    WebElement businessPlaceBtn = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[12]/div/div/button[1]"));
    businessPlaceBtn.click();
    uploadFileAfterClick();/*from  w  w  w.jav a2  s.  c o m*/
}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void uploadConfirmation() throws Throwable {
    WebElement confirmationBtn = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[13]/div/div/button[1]"));
    confirmationBtn.click();
    uploadFileAfterClick();//from   w  w  w. j  a v  a 2 s. c  o m
}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void uploadAgreement() throws Throwable {
    WebElement agreementBtn = driver.findElement(By.xpath(
            "/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[1]/div[2]/div[14]/div/div/button[1]"));
    agreementBtn.click();
    uploadFileAfterClick();//w w w  .  ja  v a2  s.c o m
}

From source file:cls.ui.model.selenium.carDealerManage.BasicInfoPage.java

public void clickSaveButton() throws Throwable {
    WebElement saveBtn = driver.findElement(
            By.xpath("/html/body/div/div[1]/div[1]/div[2]/div[1]/div/div/div/form/fieldset/div[2]/div/button"));
    saveBtn.click();
}