webdriver中模拟mobile browser的两种方式
在开发或测试时,有时需要检验一下手机上的效果,在非正式发布时,可以使用chrome来模拟mobile browser。
第一种方式是使用mobile emulation。chrome已经预定义了多种手机的参数和大小,可以使用指定的device name来模拟对应的手机浏览器来检验效果。比如:
#python
from selenium import webdriver
mobileEmulation = {'deviceName': 'iPhone X'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
driver = webdriver.Chrome(options=chrome_options)
driver.get('https://www.byincd.com')
driver.quit()
那么有哪些设备可以让我选择呢?其实在chrome的设置里已经标明了,也可以自行添加自己需要的类型参数。如下图。
第二种方式是启动浏览器时指定user agent,各种类型设备的user agent可以在这里查询:https://developers.whatismybrowser.com/ 。
#python
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--user-agent=Mozilla/5.0 (Linux; Android 9; SM-G960F Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://www.byincd.com/")
driver.quit()
当然,这两种都差不多了,可以结合在一起传递给webdriver,比如下面的是我以前写的:
#python
class SimulateMobileBrowserDriver:
@classmethod
def create(cls, device_name):
user_agents = {
"iPhone": "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Mobile/15E148 Safari/604.1",
"Android": "Mozilla/5.0 (Linux; Android 9; SM-G960F Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.157 Mobile Safari/537.36",
"iPad": "Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Mobile/15E148 Safari/604.1"
}
device_metrics = {
"iPhone": {"width": 360, "height": 640},
"Android": {"width": 360, "height": 640},
"iPad": {"width": 768, "height": 1024},
}
if device_name in user_agents.keys():
mobile_emulation = {"deviceMetrics": device_metrics[device_name], "userAgent": user_agents[device_name]}
print(mobile_emulation)
else:
mobile_emulation = {"deviceName": device_name}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
return webdriver.Chrome(options=chrome_options)
下一篇:
阿里云更新免费ssl证书用于https
上一篇:
用safari跑web自动化