一、基于java語言(轉載:http://www.mamicode.com/info-detail-1972340.html)
public class runtest {
WebDriver driver;
@BeforeClass
public void beforeClass(){
System.setProperty("webdriver.chrome.driver", "resources/chromedriver.exe");
Map<String, String> mobileEmulation = new HashMap<String, String>();
//設定裝置,例如:Google Nexus 7/Apple iPhone 6
//mobileEmulation.put("deviceName", "Google Nexus 7");
mobileEmulation.put("deviceName", "Apple iPhone 6 Plus"); //這裡是要使用的模拟器名稱,就是浏覽器中模拟器中的頂部型号
Map<String, Object> chromeOptions = new HashMap<String, Object>();
chromeOptions.put("mobileEmulation", mobileEmulation);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
try {
System.out.println("開始啟動driver~~~");
driver = new ChromeDriver(capabilities);
System.out.println("啟動driver成功~~~");
} catch (Exception e) {
System.out.println("啟動driver失敗~~~");
System.out.println(e.getMessage());
}
}
@Test
public void run(){
driver.get("http://m.baidu.com/");
System.out.println("使用浏覽器,進入到了百度頁面");
}
二、基于Python語言(轉載:http://blog.csdn.net/huilan_same/article/details/52856200)
1. 第一種方法
第一種方法是通過device name來确定我們要模拟的手機樣式,示例代碼如下:
# -*- coding: utf-8 -*-
from selenium import webdriver
from time import sleep
mobileEmulation = {\'deviceName\': \'Apple iPhone 4\'}
options = webdriver.ChromeOptions()
options.add_experimental_option(\'mobileEmulation\', mobileEmulation)
driver = webdriver.Chrome(executable_path=\'chromedriver.exe\', chrome_options=options)
driver.get(\'http://m.baidu.com\')
sleep(3)
driver.close()
如上,可直接指定deviceName,具體deviceName應該怎麼寫,可以調出開發者工具,看看Device下拉框中的選項内容。
2. 第二種方法
或者你可以直接指定分辨率以及UA辨別,如下:
# -*- coding: utf-8 -*-
from selenium import webdriver
from time import sleep
WIDTH = 320
HEIGHT = 640
PIXEL_RATIO = 3.0
UA = \'Mozilla/5.0 (Linux; Android 4.1.1; GT-N7100 Build/JRO03C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/6.3\'
mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO}, "userAgent": UA}
options = webdriver.ChromeOptions()
options.add_experimental_option(\'mobileEmulation\', mobileEmulation)
driver = webdriver.Chrome(executable_path=\'chromedriver.exe\', chrome_options=options)
driver.get(\'http://m.baidu.com\')
sleep(3)
driver.close()
上面這種方法直接指定了寬度、高度、分辨率以及ua辨別,全部可以自定義。
你也可以配合 driver.set_window_size(width,height) 來将浏覽器視窗設定為相同大小,這樣看起來更舒服一些。
現在,你可以用chrome來模拟手機浏覽器測試手機網頁了。用touch_actions來模拟手指操作吧!
