Java-Splinter: 自己对Java Selenium做了个简单封装

只是简单整合了一下常用方法

Dependencies

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>

JavaCode: Class Splinter

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Splinter {
    public ChromeDriver chromeDriver;

    boolean click(WebElement webElement) {
        try {
            webElement.click();
        } catch (Exception ignored) {
            try {
                chromeDriver.executeScript("$(arguments[0]).click()", webElement);
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    /**
     * Constructor
     */
    public Splinter() {
        if (System.getProperty("webdriver.chrome.driver") == null)
            System.setProperty("webdriver.chrome.driver",
                    "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
        chromeDriver = new ChromeDriver();
    }

    public void setText(WebElement element, String s) {
        Splinter.executeScript(this.chromeDriver, element, "arguments[0].value=\"" + s + "\"");
    }

    /**
     * Search for the element continuously until it is found.
     *
     * @param by the way to search the element
     * @return the web element
     */
    private WebElement findContinuously(By by) {
        WebElement result;
        while (true) {
            try {
                result = chromeDriver.findElement(by);
                return result;
            } catch (Exception ignored) {
//                System.err.println("Find element fail, try again");
            }
        }
    }

    /**
     * Search for the elements continuously until they are found.
     *
     * @param by the way to search the element
     * @return A list of elements
     */
    private List<WebElement> findListContinuously(By by) {
        List<WebElement> result;
        while (true) {
            try {
                result = chromeDriver.findElements(by);
                return result;
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * visit the page
     *
     * @param url url of the page
     */
    public void visit(String url) {
        this.chromeDriver.get(url);
    }

    /**
     * fill the element with a certain string
     *
     * @param webElement the element being filled
     * @param s          the string
     */
    public void fill(WebElement webElement, String s) {
        webElement.sendKeys(s);
    }

    public WebElement findElementByXpath(String xpath, boolean continuous) {
        if (continuous) {
            return findContinuously(By.xpath(xpath));
        } else return chromeDriver.findElementByXPath(xpath);
    }

    public List<WebElement> findElementsByXpath(String xpath, boolean continuous) {
        if (continuous)
            return findListContinuously(By.xpath(xpath));
        else return chromeDriver.findElementsByXPath(xpath);
    }

    public WebElement findElementByXpath(String xpath) {
        return findElementByXpath(xpath, true);
    }

    public List<WebElement> findElementsByXpath(String xpath) {
        return findElementsByXpath(xpath, true);
    }

    public WebElement findElementByXpath(WebElement webElement, String xpath, boolean continuous) {
        if (continuous) {
            WebElement result;
            while (true) {
                try {
                    result = webElement.findElement(By.xpath(xpath));
                    return result;
                } catch (Exception ignored) {
                }
            }
        } else return webElement.findElement(By.xpath(xpath));
    }

    public List<WebElement> findElementsByXpath(WebElement webElement, String xpath, boolean continuous) {
        if (continuous) {
            List<WebElement> result;
            while (true) {
                try {
                    result = webElement.findElements(By.xpath(xpath));
                    return result;
                } catch (Exception ignored) {
                }
            }
        } else return webElement.findElements(By.xpath(xpath));
    }

    public WebElement findElementByText(String text, boolean continuous) {
        return findElementByXpath("//*[text()='" + text + "']", continuous);
    }

    public List<WebElement> findElementsByText(String text, boolean continuous) {
        return findElementsByXpath("//*[text()='" + text + "']", continuous);
    }

    public WebElement findElementByText(String text) {
        return chromeDriver.findElement(By.xpath("//*[text()='" + text + "']"));
    }

    public List<WebElement> findElementsByText(String text) {
        return chromeDriver.findElements(By.xpath("//*[text()='" + text + "']"));
    }

    public WebElement findElementByAttribute(String attr, String value, boolean continuous) {
        return findElementByXpath("//*[@" + attr + "='" + value + "']", continuous);
    }

    public WebElement findElementByAttribute(String attr, String value) {
        return findElementByXpath("//*[@" + attr + "='" + value + "']", true);
    }

    public WebElement findElementById(String id, boolean continuous) {
        return findElementByXpath("//*[@id='" + id + "']", continuous);
    }

    public WebElement findElementById(String id) {
        return findElementByXpath("//*[@id='" + id + "']", true);
    }

    public void addCookie(Map<String, String> cookieMap) {
        Set<Map.Entry<String, String>> entries = cookieMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            Cookie cookie = new Cookie(entry.getKey(), cookieMap.get(entry.getValue()));
            chromeDriver.manage().addCookie(cookie);
        }
    }

    public void addCookies(Cookie[] cookies) {
        for (Cookie cookie : cookies)
            chromeDriver.manage().addCookie(cookie);
    }

    public void addCookie(Cookie cookie) {
        chromeDriver.manage().addCookie(cookie);
    }

    public void refresh() {
        chromeDriver.navigate().refresh();
    }

    public void quit() {
        chromeDriver.quit();
    }

    public void acceptAlert() {
        Alert alert = chromeDriver.switchTo().alert();
        System.out.println(alert.getText());
        alert.accept();
    }

    /**
     * switch to an another arbitrary window
     */
    public void switchToAnotherWindow() {
        Set<String> handles = chromeDriver.getWindowHandles();
        String curr = chromeDriver.getWindowHandle();
        for (String k : handles) {
            if (!k.equals(curr)) {
                WebDriver webDriver = chromeDriver.switchTo().window(k);
                this.chromeDriver = (ChromeDriver) webDriver;
                System.out.println("switch to " + webDriver.getTitle());
                break;
            }
        }
    }

    public WebDriver getDriverByPartialTitle(String title) {
        Set<String> handles = chromeDriver.getWindowHandles();
        String curr = chromeDriver.getWindowHandle();
        for (String k : handles) {
            if (k.equals(curr))
                continue;
            WebDriver webDriver = chromeDriver.switchTo().window(k);
            String currTitle = webDriver.getTitle();
            if (currTitle.contains(title)) {
                return webDriver;
            }
        }
        return null;
    }

    public void swithToByPartialText(String title) {
        WebDriver foo = getDriverByPartialTitle(title);
        if (foo != null)
            chromeDriver = (ChromeDriver) foo;
        else System.out.println("No such page");
    }

    public void close() {
        if (chromeDriver != null)
            chromeDriver.close();

    }

    public static String attributeToXpath(String attr, String value) {
        return "//*[@" + attr + "='" + value + "']";
    }

    public static void setAttribute(WebDriver driver, WebElement element, String attributename, String value) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
                element, attributename, value);
    }

    public static void executeScript(WebDriver driver, WebElement element, String script) {
        ((JavascriptExecutor) driver).executeScript(script, element);
    }

    public static void removeAttribute(WebDriver driver, WebElement element, String attributename) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].removeAttribute(arguments[1],arguments[2])", element, attributename);
    }

    static Cookie[] resolveCookies(String s) {
        ArrayList<Cookie> cookies = new ArrayList<Cookie>();
        while (s.length() != 0) {
            int index = s.indexOf('=');
            if (index == -1)
                break;
            String cookieName = s.substring(0, index).trim();
            int endIndex = s.indexOf(';');
            if (endIndex == -1)
                endIndex = s.length();
            String cookieValue = s.substring(index + 1, endIndex).trim();
            cookies.add(new Cookie(cookieName, cookieValue));
            s = s.substring(endIndex + 1);
        }

        return cookies.toArray(new Cookie[0]);
    }
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值