1. 第一种方法
通过device name来确定我们要模拟的手机样式,示例代码如下:
from selenium import webdriver
from time import sleep
mobileEmulation = {'deviceName': 'iPhone 6/7/8 Plus'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
mobile_driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
mobile_driver.get('http://m.baidu.com')
print('iphone_mobile_driver')
sleep(3)
mobile_driver.close()
2. 第二种方法
直接指定分辨率以及UA标识,如下:
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)
mobile_driver_s = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
mobile_driver_s.get('http://m.baidu.com')
print('mobile_driver')
sleep(3)
mobile_driver_s.close()
注意:我分别将两个 driver 改成了 mobile_driver、mobile_driver_s,如果继续使用driver.find_…… 会报错:
Message: no such session
image.png