由於如今項目是要作分佈式,而之前使用谷歌瀏覽器模擬手機運行作的分佈式,是指定在某臺機器運行是經過Jenkins配置,來指定服務器,可是這樣有一個問題,若是你們都同時配置到某臺電腦,那臺服務器壓力就很大,因此須要根據每臺服務器的狀況,去分配任務,那我就須要解決第一個問題,如何讓模擬器指定ip運行,個人項目的部署方式(分佈式)使用的selenium grid 的方式,使用模擬器方式最開始一直使用的是ChromeDriver方式啓動,可是這個ChromeDriver方式啓動只能是啓動本地瀏覽器,進行手機模擬,不能指定在某臺IP上進行運行java
最開始看了不少官網資料,https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation ,針對ChromeDriver java沒有辦法指定IP,而python能夠,最開始走了一大圈,想經過ChromeDriver的方法來進行改變,饒了一大圈的彎路,最後想通了一點只要更換啓動方式就能夠了python
之前啓動手機模擬代碼是這樣:web
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); }
而如今我只須要把啓動方式作更改chrome
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); } }