API启动浏览器代码(JAVA版)



    package com.ruoyi.common.spider.reptile;

    import cn.hutool.json.JSONObject;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

    /**
    * @author vmlogin
    * <dependency>
    *     <groupId> org.seleniumhq.selenium <groupId/>
    *     <artifactId> selenium-java <artifactId/>
    *     <version> 3.141.59 <version/>
    * <dependency>
    */
    public class ProductChrome {
        public static void main (String[] args) throws Exception {
            ProductChrome pc = new ProductChrome();
            String profileId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

            //根据profileId打开并获取远程调试地址
            URL url = new URL(pc.startProfile(profileId));

            //使用远程调试地址连接到打开的chrome浏览器
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.setExperimentalOption("debuggerAddress", url.getAuthority());
            WebDriver driver = new ChromeDriver(chromeOptions);

            //访问vmlogin
            driver.get("https://www.vmlogin.us/");
            System.out.println(driver.getTitle());
            driver.quit();
        }

        private String startProfile(String profileId) throws Exception {
            String url = "http://127.0.0.1:35000/api/v1/profile/start?automation=true&profileId=" + profileId;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream())
            );
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
                in.close();
                JSONObject jsonResponse = new JSONObject(response.toString());
                return jsonResponse.getStr("value");
            }
        }
    }