700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > selenium之用chrome的Mobile emulation模拟手机浏览器测试手机网页

selenium之用chrome的Mobile emulation模拟手机浏览器测试手机网页

时间:2022-04-08 16:18:19

相关推荐

selenium之用chrome的Mobile emulation模拟手机浏览器测试手机网页

很多人发现chrome有项功能,就是在开发者工具里能够模拟手机打开网页,便想能否用selenium对此进行自动化测试。答案当然是yes!

今天博主便给大家分享下如何用chrome的MobileEmulation实现手机网页自动化测试。

1.第一种方法

第一种方法是通过device name来确定我们要模拟的手机样式,示例代码如下:

# -*- coding: utf-8 -*-from selenium import webdriverfrom time import sleepmobileEmulation = {'deviceName': 'iPhone X'}options = webdriver.ChromeOptions()options.add_experimental_option('mobileEmulation', mobileEmulation)driver = webdriver.Chrome(chrome_options=options)driver.get('')sleep(3)driver.close()

如上,可直接指定deviceName,具体deviceName应该怎么写,可以调出开发者工具,看看Device下拉框中的选项内容:

2. 第二种方法

或者你可以直接指定分辨率以及UA标识,如下:

# -*- coding: utf-8 -*-from selenium import webdriverfrom time import sleepWIDTH = 320HEIGHT = 640PIXEL_RATIO = 3.0UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO}, "userAgent": UA}options = webdriver.ChromeOptions()options.add_experimental_option('mobileEmulation', mobileEmulation)driver = webdriver.Chrome(chrome_options=options)driver.get('')# 另一中调整宽高的方法driver.set_window_size(400, 640)sleep(3)driver.close()

上面这种方法直接指定了宽度、高度、分辨率以及ua标识,全部可以自定义。

你也可以配合 driver.set_window_size(width,height) 来将浏览器窗口设置为相同大小,这样看起来更舒服一些。

现在,你可以用chrome来模拟手机浏览器测试手机网页了。用touch_actions来模拟手指操作吧!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。