1.背景
因為現在項目是要做分布式,而以前使用谷歌瀏覽器模擬手機運行做的分布式,是指定在某台機器運行是通過Jenkins配置,來指定服務器,但是這樣有一個問題,如果大家都同時配置到某台電腦,那台服務器壓力就很大,所以需要根據每台服務器的情況,去分配任務,那我就需要解決第一個問題,如何讓模擬器指定ip運行,我的項目的部署方式(分布式)使用的selenium grid 的方式,使用模擬器方式最開始一直使用的是ChromeDriver方式啟動,但是這個ChromeDriver方式啟動只能是啟動本地瀏覽器,進行手機模擬,不能指定在某台IP上進行運行
最開始看了很多官網資料,https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation ,針對ChromeDriver java沒有辦法指定IP,而python可以,最開始走了一大圈,想通過ChromeDriver的方法來進行改變,饒了一大圈的彎路,最后想通了一點只要更換啟動方式就可以了

以前啟動手機模擬代碼是這樣:
public void initdriver(){
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-infobars");
Map<String, Object> prefs = new HashMap<String, Object>();
// 是否加載圖片
// prefs.put("profile.managed_default_content_settings.images", 2);
options.setExperimentalOption("prefs", prefs);
Map<String, Object> deviceMetrics = new HashMap<String, Object>();
deviceMetrics.put("width", 360);
deviceMetrics.put("height", 640);
deviceMetrics.put("pixelRatio", 3.0);
Map<String, Object> mobileEmulation = new HashMap<String, Object>();
mobileEmulation.put("deviceMetrics", deviceMetrics);
mobileEmulation.put("userAgent",
"Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");
options.setExperimentalOption("mobileEmulation", mobileEmulation);
System.setProperty("webdriver.chrome.driver", "resources/chromedriver.exe");
driver = new ChromeDriver(options);
}
而現在我只需要把啟動方式做更改
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-infobars");
Map<String, Object> prefs = new HashMap<String, Object>();
// 是否加載圖片
// prefs.put("profile.managed_default_content_settings.images", 2);
options.setExperimentalOption("prefs", prefs);
Map<String, Object> deviceMetrics = new HashMap<String, Object>();
deviceMetrics.put("width", 360);
deviceMetrics.put("height", 640);
deviceMetrics.put("pixelRatio", 3.0);
Map<String, Object> mobileEmulation = new HashMap<String, Object>();
mobileEmulation.put("deviceMetrics", deviceMetrics);
mobileEmulation.put("userAgent",
"Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19");
options.setExperimentalOption("mobileEmulation", mobileEmulation);
System.setProperty("webdriver.chrome.driver", "resources/chromedriver.exe");
if(TestngListener2.getProjectCode().contains("platform")){//這里表示使用的平台,為了不影響以前框架使用
System.out.println("使用的平台進行啟動的瀏覽器");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
try {
driver = new RemoteWebDriver(new URL("http://10.40.2.114:5555/wd/hub"), capabilities);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}else{
driver = new ChromeDriver(options);
}
}
