如何在selenium中设置chrome mobile模拟器的设备指标参数?

时间:2017-09-19 19:49:47

标签: java selenium-webdriver emulation selenium-chromedriver mobile-chrome

我正在尝试自动化chrome在selenium中提供的移动模拟器,但是,我目前面临的问题是浏览器打开了错误的设备指标,我试图专门设置高度和宽度但没有任何运气,这是我的代码:

Map<String, Object> deviceMetrics = new HashMap<String, Object>();
            deviceMetrics.put("width", 360);
            deviceMetrics.put("height", 640);
            Map<String, Object> mobileEmulation = new HashMap<String, Object>();
            mobileEmulation.put("deviceMetrics", deviceMetrics);
            mobileEmulation.put("deviceName", "Nexus 5");
            Map<String, Object> chromeOptions = new HashMap<String, Object>();
            chromeOptions.put("mobileEmulation", mobileEmulation);
            DesiredCapabilities capabilityMob = DesiredCapabilities.chrome();
            capabilityMob.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
            this.driver = new RemoteWebDriver(_url, capabilityMob);

但是我收到以下错误:

  

org.openqa.selenium.WebDriverException:未知错误:无法解析   功能:来自未知错误的chromeOptions:无法解析   来自未知错误的mobileEmulation:'deviceName'必须单独使用

1 个答案:

答案 0 :(得分:0)

您不需要同时使用预安装的设备和自定义设备参数。 尝试类似:

Map<String, Object> deviceMetrics = new HashMap<>();
deviceMetrics.put("width", 768);
deviceMetrics.put("height", 1024);
deviceMetrics.put("pixelRatio", 2);
Map<String, Object> mobileEmulation = new HashMap<>();
mobileEmulation.put("deviceMetrics", deviceMetrics);
mobileEmulation.put("userAgent", "Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 
Safari/9537.53");
Map<String, Object> chromeOptions = new HashMap<>();
chromeOptions.put("mobileEmulation", mobileEmulation);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);