Selenium如何在谷歌瀏覽器模擬H5頁面
阿新 • • 發佈:2018-12-12
一、基於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來模擬手指操作吧!