社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在移动仿真模式下运行Selenium Python?

Cerin • 3 年前 • 1504 次点击  

如何使用Selenium在移动仿真模式下打开Chrome?

根据 these docs 您应该能够在移动仿真模式下启动Chrome,您通常可以通过Inspect面板访问该模式,使用:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
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" }
chrome_options = Options()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(chrome_options=chrome_options)

然而,用最新版本的Chrome和ChromeDriver进行测试表明,它不起作用。它可以打开Chrome浏览器,但它处于正常的桌面模式。所有的移动选项似乎都被完全忽略了。

我仍然可以在Selenium创建的浏览器中手动启用移动仿真,但这对自动化测试没有帮助。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130453
 
1504 次点击  
文章 [ 1 ]  |  最新文章 3 年前
PDHide
Reply   •   1 楼
PDHide    4 年前

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">TEST</button>

<script type="text/javascript">
        $('#test').on('touchend click',function(e){
  if(e.type=='click')
    alert('click triggered');
  else
    alert('touch triggered');
});
    </script>

将上面的html复制到一个文件中,然后从selenium打开它。

现在运行代码,你可以看到你得到触摸触发警报,而不是点击触发:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
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"}


chrome_options = webdriver.ChromeOptions()

chrome_options.add_experimental_option(
    "mobileEmulation", mobile_emulation)

driver = webdriver.Chrome(options=chrome_options)

driver.get(
    "file:///C:/Users/prave/Desktop/push.html")

driver.find_element_by_tag_name("button").click()
input()

输出:

该浏览器看起来像普通浏览器,但当您打开任何url usign驱动程序时,屏幕分辨率将是移动设备的分辨率。得到(“”)

enter image description here