通过Python3+selenium自动测试网页

使用的是selenium,最开始接触这个模块包是爬虫,这次是工作需要来自动测试网页。

记录一下模拟不同浏览器的方式

  • 总共测了两个浏览器,Firefox在centos7上和chrome在win10上。都是模拟的IPAD方式访问,原因是使用模拟手机的话,会有部分内容被挡住导致无法模拟点击,┑( ̄Д  ̄)┍无奈。
  • so,模拟手机和模拟IPAD是同样的操作,只是把对应IPAD的内容换成想要的手机就可以了。
from selenium import webdriver

# 使用Firefox手机浏览器
user_agent = "Mozilla/5.0 (iPad; CPU OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1"
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", user_agent)
driver = webdriver.Firefox(profile, executable_path="geckodriver")
# 设置窗口大小
driver.set_window_size(1080, 1920)
testUrl = 'www.baidu.com'  # 已替换
# 加载指定的网址
driver.get(testUrl)

# 模拟chrome手机浏览器
mobileEmulation = {'deviceName': 'iPad'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
testUrl = 'www.baidu.com'  # 已替换
driver.get(testUrl)
# 设置窗口大小
driver.set_window_size(1024, 1366)

###
实现逻辑
###

可以注意到:

Firefox和chrome对于模拟手机的设置方式不同。
Firefox是通过改变响应头来模拟,chrome是有固定的设备选项。

猜你喜欢

转载自blog.51cto.com/feature09/2390535