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

Selenium(C#)如何自动打开Chrome DevTools并切换到移动端视图?

在C# Selenium中打开Chrome时自动开启DevTools并切换到移动端视图

要实现同时打开Chrome、DevTools并切换到移动端视图,单纯用EnableEmulation仅能调整分辨率,需结合Chrome DevTools Protocol (CDP)的多个命令,同时配置Chrome启动参数。以下是可行的实现方案:

关键步骤与代码示例

  1. 配置Chrome启动参数:添加--auto-open-devtools-for-tabs确保新标签页自动打开DevTools。
  2. 通过CDP设置设备模拟:指定Pixel 5的参数并标记为移动设备。
  3. 开启触摸模拟:还原移动端交互特性。
  4. 显示设备框架:触发DevTools切换到带设备边框的移动端视图模式。
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.DevTools.V118.Emulation; // 版本需与Chrome对应
using OpenQA.Selenium.DevTools.V118.Overlay;

// 配置Chrome启动选项
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--auto-open-devtools-for-tabs");

// 初始化ChromeDriver
using var driver = new ChromeDriver(chromeOptions);

// 获取DevTools会话
var devToolsSession = driver.GetDevToolsSession();

// 设置Pixel 5的设备参数
var deviceMetricsCmd = new SetDeviceMetricsOverrideCommandSettings
{
    Width = 393,
    Height = 851,
    DeviceScaleFactor = 2.75,
    Mobile = true,
    ScreenOrientation = new ScreenOrientation
    {
        Angle = 0,
        Type = ScreenOrientationType.PortraitPrimary
    }
};
await devToolsSession.SendCommand(deviceMetricsCmd);

// 开启触摸模拟
await devToolsSession.SendCommand(new SetTouchEmulationEnabledCommandSettings
{
    Enabled = true,
    MaxTouchPoints = 5
});

// 显示设备框架(切换到移动端视图)
await devToolsSession.SendCommand(new SetShowDeviceFrameCommandSettings
{
    Show = true
});

// 导航到目标页面
driver.Navigate().GoToUrl("https://example.com");

注意事项

  • DevTools版本匹配:代码中的V118需替换为当前Chrome浏览器的版本号,可通过Chrome设置的「关于Chrome」查看。
  • 旧版Selenium兼容:若使用Selenium 4.x之前的版本,需调整DevTools会话的获取方式,可通过IDevTools接口实现。

内容的提问来源于stack exchange,提问作者Timor Tagiev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:15:43