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


package com.ruoyi.threed;


import com.alibaba.fastjson2.JSONObject;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
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;
import java.util.Map;

public class BrowserProfile {
    public static void main(String[] args) throws Exception {
        BrowserProfile bp = new BrowserProfile();

        String profileId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

        String ss = bp.startProfile(profileId);
        System.out.println("ss:"+ss);


        Map<String,Object> _map =  JSONObject.parseObject( ss.toString(),Map.class);
        String vaa = _map.get("value").toString();
        System.out.println("value()"+vaa.toString());
        URL url = new URL(vaa);
        String  dizip =url.getAuthority().replace("http://","");
        System.out.println("dizip:"+dizip);

        String drvstr = _map.get("chromedriver").toString();

        System.setProperty("webdriver.chrome.driver",drvstr);
       
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("debuggerAddress",dizip);
        WebDriver driver = new ChromeDriver(options);
  

        //访问vmlogin
        driver.navigate().to("http://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?skiplock=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();
        System.out.println("response.toString()"+response.toString());
    
        Thread.sleep(3000);
        return response.toString();
    }
}