在使用Chrome浏览网页时,我们可以使用Chrome开发者工具模拟手机浏览器,在使用Selenium操作Chrome时同样也可以模拟手机浏览器。
操作方法非常简单,在ChromeOptions()浏览器选项,添加实验选项,mobileEmulation选项中通过devicename指定选择的设备即可,操作代码如下。
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option(\'mobileEmulation\',{\'deviceName\': \'iPhone X\'}) # 模拟iPhone X浏览
driver = webdriver.Chrome(options=options)
driver.get(\'http://m.baidu.com\')
Chrome开发者工具中已经设置好的设备类型非常多,可以在开发者工具->Settings->Devices中查看
使用自定义设备
mobileEmulation除了可以通过deviceName指定设备之外,还可以通过deviceMetrics指定设备指标,一般设备指标包含
- width: 设备宽度
- height: 设备高度
- piexelRatio: 设备像素密度
- userAgent:设备浏览器标识
如下:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option(\'mobileEmulation\', {\'deviceMetrics\':{\'width\': 320, \'height\': 640, \'piexelRatio\': 3.0, \'userAgent\': \'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\'}})
driver = webdriver.Chrome(options=options)
driver.get(\'http://m.baidu.com\')