Selenium如何在谷歌瀏覽器模擬H5頁面

 

1、基於java語言(轉載:http://www.mamicode.com/info-detail-1972340.html)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("使用瀏覽器,進入到了百度頁面"); }
複製代碼

2、基於Python語言(轉載:http://blog.csdn.net/huilan_same/article/details/52856200)java

複製代碼
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來模擬手指操做吧!
相關文章
相關標籤/搜索