如何使用selenium 驱动chrome浏览器并且打开方式为手机模式

随着移动设备使用率的不断增加,移动页面的测试也变得越来越重要。

对于互联网公司M站的测试,如果不通过专用的appium等移动端测试工具是否还有方便快捷的办法呢?答案当然是有啊。

使用chrome driver和chrome浏览器并进入chrome的 toggle device mode 模式,就可以很好的模拟手机端,下面直接上代码。

import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Navigation;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class TestH5 {
    public static void main(String args[]) {
        System.setProperty("webdriver.chrome.driver", "E:/Selenium/2016-07-14/chromedriver.exe");
        Map<String, String> mobileEmulation = new HashMap<String, String>();
        mobileEmulation.put("deviceName", "Google Nexus 5");
        Map<String, Object> chromeOptions = new HashMap<String, Object>();
        chromeOptions.put("mobileEmulation", mobileEmulation);
        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        WebDriver driver = new ChromeDriver(capabilities);
        Navigation navigation = driver.navigate();
        navigation.to("https://m.baidu.com/");
        String title = driver.getTitle();
        System.out.println("title:" + title);
    }
}

使用的chrome版本和chromedriver版本,这两个如果配合不好会有坑。

 

Chromedriver版本为2.53.1

转载:http://www.cnblogs.com/iamhp/p/6016194.html

posted @ 2017-08-13 17:06  SunnyCC  阅读(2251)  评论(0编辑  收藏  举报