selenium webdriver 常用方法

    /**
     * 判断元素是否存在
     * 
     * @param driver
     * @param by
     * @return
     */
    public static boolean isElementPresent(WebDriver driver, By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    /**
     * 判断Alert是否存在
     * 
     * @param driver
     * @return
     */
    public static boolean isAlertPresent(WebDriver driver) {
        try {
            driver.switchTo().alert();
            return true;
        } catch (NoAlertPresentException e) {
            return false;
        }
    }

    /**获取弹框的文本
     * @param driver
     * @param acceptNextAlert,true接受
     * @return
     */
    public static String closeAlertAndGetItsText(WebDriver driver,
            boolean acceptNextAlert) {
        try {
            Alert alert = driver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }

 

posted @ 2013-08-24 16:53  苦逼IT男  阅读(440)  评论(0编辑  收藏  举报