Selenium如何在谷歌浏览器模拟H5页面

一、基于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来模拟手指操作吧!

 

posted @ 2017-10-19 17:47  yuxuefeng  阅读(4423)  评论(0编辑  收藏  举报