更改PC端Chrome浏览器的属性值,将PC端Chrome浏览器设定为手机端尺寸的浏览器。
#!usr/bin/env python #-*- coding:utf-8 -*- #修改Chrome设置伪装成手机M站 from selenium import webdriver import unittest,time class TestDemo(unittest.TestCase): def test_ipadChrome(self): options = webdriver.ChromeOptions() #--user-agent=‘xxxx‘来修改HTTP请求头部的Agent字符串,以便将PC端的Chrome浏览器伪装成手机浏览器 options.add_argument(‘--user-agent=Mozilla/5.0(iPad;CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (Khtml,like Gecko)Version/5.1 Mobile/9A334 Safari/7534.48.3‘) driver = webdriver.Chrome(chrome_options=options) driver.get(‘http://www.baidu.com‘) time.sleep(3) driver.find_element_by_id(‘kw‘).send_keys(‘iPad‘) time.sleep(2) #查看伪装效果 driver.get(‘about:version‘) time.sleep(10) driver.quit() def test_iPhoneChrome(self): options = webdriver.ChromeOptions() options.add_argument(‘--user-agent=Mozilla/5.0(iPhone;CPU iPhone 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML,like Gecko)Version/5.1 Mobile/9A334 Safari/7534.48.3‘) driver = webdriver.Chrome(chrome_options=options) driver.get(‘http://www.baidu.com‘) time.sleep(2) driver.find_element_by_id(‘index-kw‘).send_keys(‘iPhone‘) time.sleep(2) driver.get(‘about:version‘) time.sleep(10) driver.quit() def test_android236Chrome(self): options = webdriver.ChromeOptions() options.add_argument(‘--user-agent=Mozilla/5.0(Linux;U;Android 2.3.6;en-us; Nexus S Build/GRK39F)AppleWebKit/533.1 (KHTML,like Gecko)Version/4.0 Mobile Safari/533.1‘) driver = webdriver.Chrome(chrome_options=options) driver.get(‘http://www.baidu.com‘) time.sleep(2) driver.find_element_by_id(‘index-kw‘).send_keys(‘Android 2.3.6‘) time.sleep(2) driver.get(‘about:version‘) time.sleep(10) driver.quit() def test_Android402Chrome(self): options = webdriver.ChromeOptions() options.add_argument(‘--user-agent=Mozilla/5.0(Linux;U;Android 4.0.2;en-us; Galaxy Nexus Build/ICL53F)AppleWebKit/534.30 (KHTML,like Gecko)Version/4.0 Mobile Safari/534.30‘) driver = webdriver.Chrome(chrome_options=options) driver.get(‘http://www.baidu.com‘) time.sleep(2) driver.find_element_by_id(‘index-kw‘).send_keys(‘Android 4.0.2‘) time.sleep(2) driver.get(‘about:version‘) time.sleep(10) driver.quit() if __name__ == ‘__main__‘: unittest.main()