Python

来源:互联网 发布:2016淘宝818活动 编辑:程序博客网 时间:2024/05/19 22:52

Python - Selenium Chrome 模拟手机

Max.Bai

2017-04


Chrome浏览器支持移动端调试,当然ChromeDriver也支持移动端测试了。

使用python调用Webdriver 的Chrome浏览器驱动,并设置对应的options就可以实现浏览器打开后为移动端模式。

RobotFramework - Chrome模拟手机

1. 简单模式,指定对应的手机设备即可

mobile_emulation = {"deviceName":"Google Nexus 5"}
完整代码

# -*- coding:utf-8 -*-import timefrom selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsmobile_emulation = {"deviceName":"Google Nexus 5"}chrome_options = Options()chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)driver = webdriver.Chrome(chrome_options = chrome_options)driver.get("http://www.baidu.com")time.sleep(5)driver.close()


2. 复杂模式,可以设置设备的宽度等等等

可包含deviceMetrics, userAgent

mobile_emulation = {    "deviceMetrics": { "width": 360, "height": 640, "pixelRatio": 3.0 },    "userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19" }

完整代码同简单模式,替换下就可以


3. Grid模式下创建webdriver

Grid是Selenium分布式执行模式(搭建分布式)

和本地模式不同的是需要使用Remote方法。

实例代码:

# -*- coding:utf-8 -*-import timefrom selenium import webdrivermobile_emulation = { "deviceName": "Google Nexus 5" }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())driver.get("http://www.baidu.com")time.sleep(5)driver.close()

最后附一张截图,看看浏览器打开是什么样子的




相关文档:

https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation




0 0