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); } }