Python Selenium模拟手机端浏览器失败,如何实现目标效果?
Selenium模拟移动端浏览器失效解决方法
问题说明
你尝试通过两种方式用Selenium模拟移动端浏览器,但仅实现了窗口缩小,未加载移动端页面:
- 自定义设备参数(宽高、像素比、User-Agent)
- 指定设备名为"iPhone 12 Pro"
你的代码存在语法和API使用错误,导致模拟失效,以下是修正方案:
代码错误点
mobile2 = {"deviceName", "iPhone 12 Pro"}是集合而非字典,正确格式应为键值对(冒号分隔)options = options.Options()初始化方式错误,需正确导入并实例化ChromeOptions- 新版Selenium已弃用
desirable_capabilities参数,直接传入options即可
正确代码示例
方式一:指定设备名模拟
from selenium import webdriver from selenium.webdriver.chrome.options import Options # 初始化Chrome选项 options = Options() # 用字典格式配置设备名 mobile_emulation = {"deviceName": "iPhone 12 Pro"} options.add_experimental_option("mobileEmulation", mobile_emulation) # 启动浏览器并访问目标站点 browser = webdriver.Chrome(options=options) browser.get("https://example.com")
方式二:自定义设备参数模拟
from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() # 自定义设备参数(宽高、像素比、User-Agent) mobile_emulation = { "deviceMetrics": {"width": 400, "height": 822, "pixelRatio": 3.0}, "userAgent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Mobile Safari/537.36" } options.add_experimental_option("mobileEmulation", mobile_emulation) browser = webdriver.Chrome(options=options) browser.get("https://example.com")
注意事项
- 确保ChromeDriver版本与本地Chrome浏览器版本完全匹配,版本不兼容会导致模拟失败
- 部分网站会通过触摸支持等额外维度检测设备,Selenium的
mobileEmulation已默认配置相关参数,无需手动添加 - 若仍加载PC页面,可尝试清除浏览器缓存后重新测试
内容的提问来源于stack exchange,提问作者puppet
相关产品推荐
相关产品推荐

