近段时间测试H5页面,使用chrome浏览器然后F12切换到手机模式;刚开始使用selenium框架然后再模拟操作F12,但是发现切换到手机模式后又恢复到浏览器的原始模式了,后来就各种百度,终于找到答案了,以下是示例代码

# -*- coding: utf-8 -*-

from selenium import webdriver
from time import sleep

protocol='http'
url=protocol+'://m.baidu.com'

mobileEmulation = {'deviceName': 'iPhone 6'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)

driver.get(url)

class OpenH5():
    def openBaidu(self):
        #driver=self.driver
        print "点击输入框"
        driver.find_element_by_id("index-kw").clear()
    
        driver.find_element_by_id("index-kw").send_keys(u"测试")
        
        driver.find_element_by_id("index-bn").click()
        driver.get_screenshot_as_file("../../screen/chaweizhang.png")
        sleep(3)
        #driver.find_element_by_xpath(".//*[@id='app']/div/div/div[3]/ul/li[3]/span[text()='活动']").click()
        print u'关闭浏览器'
        
        driver.quit()
        
login1 =OpenH5()
login1.openBaidu()
sleep(5)