Error: There is already an option for the mobileEmulation capability. Please use that instead. Parameter name: capabilityName

Error: There is already an option for the mobileEmulation capability. Please use that instead. Parameter name: capabilityName

我已经将 Selenium Webdriver C# 更新到 2.50.0 版,不幸的是我也将 ChromeDriver 更新到 2.21 版,然后我遇到了一个问题。我倾向于认为它与新版本的 ChromeDriver 有关,但我也不确定新版本的 Selenium。

我用了下一段代码运行手机模拟:

var mobileEmulation = new Dictionary<string, string>
{
     {"deviceName", device}
};

ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("mobileEmulation", mobileEmulation);

这很有效。

现在在下一个字符串:

options.AddAdditionalCapability("mobileEmulation", mobileEmulation);

它告诉我下一个错误:

There is already an option for the mobileEmulation capability. Please use that instead. Parameter name: capabilityName

那么在这个方法中我应该使用什么作为第一个参数呢?

该检查不到一天前添加到 Selenium 2.50 中:

https://github.com/SeleniumHQ/selenium/commit/6db8a5fd2bf8a1fc89d41467d1f21d073ffadfe0

我没有找到任何文档,但您似乎需要使用新的类型安全 ChromeMobileEmulationDeviceSettings class 来设置移动仿真选项。希望从上面的差异中可以清楚地看出您需要更改什么。

这里正确的做法是在 ChromeOptions 对象上使用 EnableMobileEmulation 方法。有两个重载。第一个重载采用一个字符串,该字符串旨在与设备名称一起使用。第二个重载采用 ChromeMobileEmulationDeviceSettings 对象,您可以在该对象上设置高度、宽度和像素比率等内容。此方法允许使用类型安全参数,并允许您正确设置 mobileEmulation 功能。代码看起来像这样:

// Assumes deviceName is a string variable containing the name
// of the device to emulate.
ChromeOptions options = new ChromeOptions();
options.EnableMobileEmulation(deviceName);

注意:此答案指的是 .NET 绑定的 2.50.1 版本,它更正了这方面的 API。