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

Selenium Chrome移动端模拟失效:代码问题排查与修复请求

代码问题排查与修复

存在的问题

  • 参数名称过时:webdriver.Chrome的chrome_options参数已被废弃,新版Selenium需要使用options参数传递配置。
  • User-Agent版本过旧:代码中使用的Chrome 18版本UA过于老旧,部分网站无法识别为移动端设备,导致页面仍以桌面模式渲染。
  • 手动配置设备参数易出错:手动设置宽高和像素比可能存在匹配偏差,不如直接使用Chrome预设的设备配置更准确。

修复后的代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 方案1:使用预设设备名称(推荐)
mobile_emulation = {"deviceName": "iPhone 11"}

# 方案2:自定义更新的UA与设备参数(按需使用)
# mobile_emulation = {
#     "deviceMetrics": {"width": 375, "height": 812, "pixelRatio": 3.0},
#     "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"
# }

chrome_options = Options()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
# 使用正确的options参数传递配置
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.whatismybrowser.com/detect/what-is-my-user-agent/")

额外说明

  • 优先选择预设设备名称的配置方式,Chrome会自动匹配对应设备的UA、屏幕尺寸和像素比,避免手动配置的误差。
  • 若需自定义UA,建议通过真实移动端浏览器访问检测网站获取最新的UA字符串,确保兼容性。

内容的提问来源于stack exchange,提问作者Subhash Prajapati

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:30:56