一、如果chrome选项里边有这个模拟设备(比如iPhone 6 Plus):
1、先启动Selenium Grid, 比如命令:java -jar selenium-server-standalone-XXX.jar。
2、代码如下:
#coding=utf-8 from selenium import webdriver mobile_emulation = { "deviceName": "iPhone 6 Plus" } chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities = chrome_options.to_capabilities())
二、如果chrome选项里边没有预置这个模拟设备,也可以自己配置,代码如下:
#coding=utf-8 from selenium import webdriver mobile_emulation = { "deviceMetrics": { "width": 414, "height": 736, "pixelRatio": 3.0 }, "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1" } chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Chrome(chrome_options = chrome_options)
三、修改浏览器的User-Agent来伪装你的浏览器访问手机m站,代码如下:
#coding=utf-8 from selenium import webdriver chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1')
driver = webdriver.Chrome(chrome_options = chrome_options)