You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium 4 Python移动端模拟如何设置横屏模式?

解决Selenium移动端模拟横屏的问题

你遇到的错误是因为Selenium的mobileEmulation配置规则——使用deviceName时不能搭配其他参数,以下两种方法可以实现横屏模拟:

  • 方法一:手动配置设备参数+横屏
    直接指定设备的宽、高、像素比,同时设置横屏方向。以iPhone SE为例,横屏时分辨率为原竖屏的宽高互换,代码示例:

    options.add_experimental_option(
        "mobileEmulation", {
            "deviceMetrics": {
                "width": 667,
                "height": 375,
                "pixelRatio": 2.0
            },
            "deviceOrientation": "landscape",
            "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
        }
    )
    

    注:userAgent可使用对应设备的官方UA字符串,确保页面能正确识别设备类型。

  • 方法二:先启动竖屏设备,再切换横屏
    先通过deviceName正常启动移动端模拟,再调用Chrome DevTools API强制切换横屏:

    # 先启动iPhone SE竖屏模拟
    options.add_experimental_option(
        "mobileEmulation", {
            "deviceName": "iPhone SE",
        }
    )
    driver = webdriver.Chrome(options=options)
    
    # 切换为顺时针90度横屏
    driver.execute_cdp_cmd("Emulation.setDeviceOrientationOverride", {
        "alpha": 0,
        "beta": 0,
        "gamma": 90
    })
    

    注:gamma设为-90可实现逆时针90度横屏,按需调整即可。

内容的提问来源于stack exchange,提问作者greg pinakapoging nilalang sa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 23:43:15