Java+selenium+chrome+linux/windows实现数据获取

背景:在进行业务数据获取或者自动化测试时,通常会使用模拟chrome方式启动页面,然后获取页面的数据。在本地可以使用windows的chromedriver.exe进行打开chrome页面、点击等操作。在linux 下通常使用无界面无弹窗的方式进行操作。接下来是实现方案。

代码层面:

关键工具类:ChromeDriverUtil
public class ChromeDriverUtil {
    public WebDriver getWebDriver() {
        ChromeOptions options = new ChromeOptions();
        String driverPath = ChromeDriverUtil.getDriverPath(options);
        System.setProperty("webdriver.chrome.driver", driverPath);
        options.addArguments("--remote-allow-origins=*");
        WebDriver driver = new ChromeDriver(options);
        // 设置最长等待时间
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        return driver;
    }

    public static String getDriverPath(ChromeOptions options) {
        String driverPath = "";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            driverPath = "chromedriver-win64/chromedriver.exe";
        } else if (os.contains("nix") || os.contains("nux")) {
            driverPath = "chromedriver-linux64/chromedriver";
            // 设置无界面模式
            options.addArguments("--headless");
            options.addArguments("--no-sandbox");
            log.info("————————————————————————————————linux开启无界面模式设置————————————————————————————————");
        } else {
            throw new RuntimeException("Unsupported operating system: " + os);
        }
        return driverPath;
    }

    public static int getSleepRandom() {
        Random random = new Random();

        // Define the lower and upper bounds
        int lowerBound = 6000;
        int upperBound = 8000;

        // Generate a random integer between lowerBound and upperBound (inclusive)
        return random.nextInt(upperBound - lowerBound + 1) + lowerBound;
    }

    public static String extractDate(String url) {
        // 正则表达式匹配 announcementTime 参数
        Pattern pattern = Pattern.compile("announcementTime=(\\d{4}-\\d{2}-\\d{2})");
        Matcher matcher = pattern.matcher(url);

        // 查找匹配项并返回日期
        if (matcher.find()) {
            return matcher.group(1); // 获取第一个捕获组,即日期部分
        }
        return null; // 如果没有匹配项,则返回 null
    }


    // 等待一定时间
    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 判断某个元素是否存在


    public static double parseDoubleStr(String doublestr) {
        if (doublestr.equals("-")) {
            return 0.0;
        } else {
            return Double.parseDouble(doublestr.replaceAll(",", ""));
        }
    }

    public static long parseLongStr(String longstr) {
        // System.out.println("longstr=" + longstr);
        int flag = 1;
        if (longstr.contains("-1")) {
            flag = -1;
        }
        longstr = longstr.replaceAll("-", "");
        longstr = longstr.replaceAll(",", "");
        // 如果有小数点
        if (longstr.contains(".")) {
            longstr = longstr.replaceAll("\\.", "");
            return Long.parseLong(longstr) * 100 * flag;
        } else { // 没有小数点
            return Long.parseLong(longstr) * 10000 * flag;
        }
    }


    // 关闭当前窗口
    public static void closeWindow(WebDriver driver) {
        // 获取所有句柄的集合
        List winHandles = new ArrayList<>(driver.getWindowHandles());
        driver.switchTo().window(winHandles.get(0));
        driver.close();
        log.info("————————————————————————————————页面关闭————————————————————————————————");
    }
}

使用使用时:

public class Demo{

   public static void main(String[] args) throws IOException, InterruptedException {
        WebDriver driver = new ChromeDriverUtil().getWebDriver();
        String SEARCH_URL="XXXX";
        driver.get(SEARCH_URL);
        log.info("开始获取页面数据!!!---------------" + driver.getCurrentUrl());
        //todo 处理过程

        ChromeDriverUtil.closeWindow(driver);
    }


}

windows环境:

windows环境下在src目录平级下增加驱动文件夹chromedriver-win64,即可直接使用。本项目所使用的包chromedriver-win64.zip

linux环境:

linux环境需要在linux下载chrome、chrome驱动。

chrome下载(我用的是124版本):

//创建目录
mkdir chrome

//下载rpm
wget http://dist.control.lth.se/public/CentOS-7/x86_64/google.x86_64/google-chrome-stable-124.0.6367.118-1.x86_64.rpm

//install 
yum install google-chrome-stable-124.0.6367.118-1.x86_64.rpm 

//查看版本
google-chrome --version

看到版本后就是下载成功了

接下来就是下载驱动,可自己从Chrome for Testing availability获取。我是用的是

https://storage.googleapis.com/chrome-for-testing-public/125.0.6422.4/linux64/chromedriver-linux64.zip

然后将这个文件夹解压后,放在与jar平级目录。(这个要根据自己的项目放置,或者直接用绝对路径)

Java+selenium+chrome+linux/windows实现数据获取_第1张图片还需要给chromedriver-linux64文件夹下的chromedriver赋权限,

chmod +x chromedriver

然后就可以使用了。

遇到的问题:

1. linux安装chrome的时候报错软件包:google-chrome-stable-128.0.6613.119-1.x86_64 (/google-chrome-stable_current_x86_64)           需要:libc.so.6(GLIBC_2.25)(64bit)

解决:应该是chrome版本与centos7版本不匹配,后面我下载了124版本的就可以了。

2. 报错session not created: DevToolsActivePort file doesn't exist

解决:这个应该是没有弄好chrome和chromedriver版本的问题,如果使用的是我用的124版本就是用我提供的driver就行了。

3. 运行报错The process started from chrome location /opt/google/chrome/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed

解决:大概的意思就是没有启动成功,打开浏览器失败了,因为是linux,所以不需要弹窗启动浏览器,所以需要增加设置使用无弹窗方式启动。所以在ChromeDriverUtil中对Linux环境做了设置增加参数。

options.addArguments("--headless");
options.addArguments("--no-sandbox");

然后就可以正常运行了。

你可能感兴趣的:(Java,selenium,chrome,测试工具,java,linux,windows)