在Selenium 2.39及之前使用c#,您可以直接与ChromeOptions和DesiredCapabilities进行交互。因此,如果您想在现代版本的Windows上模拟Android设备,您的代码段可能如下所示:
// Define the ChromeOptions to make Chrome act like a mobile device
ChromeOptions options = new ChromeOptions();
options.AddArgument("--user-agent=Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19");
options.AddArgument("--disable-sync-passwords");
Capabilities = DesiredCapabilities.Chrome();
//Needed to find Win7 VM rather than Linux or Mac
Capabilities.SetCapability("platform", "VISTA");
//CEF apps are also tested using Selenium2 and Grid.
//A version of "real" has been created in my Grid config to ensure
//I target current Chrome and not CEF.
Capabilities.SetCapability("version", "real");
Capabilities.SetCapability(ChromeOptions.Capability, options);
//Get a new RemoteWebDriver that thinks it is an Android device
Driver = new RemoteWebDriver(new Uri(Settings.RemoteWebDriverSettings.GridLocation), Capabilities);
//Resize for mobile
Driver.Manage().Window.Position = new System.Drawing.Point(0, 0);
Driver.Manage().Window.Size = new System.Drawing.Size(400, 680);
然而,在Selenium 2.40及更高版本中,已经发生了一些改变,打破了.net的这种方法。我能找到的改变的最佳解释来自this exchange here,其中指出:
.NET绑定正朝着DesiredCapabilites不应直接使用的模式发展,即使使用RemoteWebDriver也是如此。为此,ChromeOptions类具有ToCapabilities()方法。
尽我所能,我找不到在使用ChromeOptions时如何设置目标平台和版本的好例子。
在某些时候,我想利用最近版本的ChromeDriver引入的新MobileEmulation,但我必须首先克服这个障碍。
非常感谢任何帮助。
答案 0 :(得分:1)
从Selenium项目成员can be seen here获得答案。
上面的代码片段会变成这样的东西,而不是:
// Define the ChromeOptions to make Chrome act like a mobile device
ChromeOptions options = new ChromeOptions();
options.AddArgument("--user-agent=Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19");
options.AddArgument("--disable-sync-passwords");
//You can cast the ICapabilities object returned by ToCapabilities() as DesiredCapabilities
capabilities = options.ToCapabilities() as DesiredCapabilities;
//Needed to find Win7 VM rather than Linux or Mac
capabilities.SetCapability("platform", "VISTA");
//CEF apps are also tested using Selenium2 and Grid.
//A version of "real" has been created in my Grid config to ensure
//I target current Chrome and not CEF.
capabilities.SetCapability("version", "real");
//Get a new RemoteWebDriver that thinks it is an Android device
Driver = new RemoteWebDriver(new Uri(Settings.RemoteWebDriverSettings.GridLocation), capabilities);
//Resize for mobile
Driver.Manage().Window.Position = new System.Drawing.Point(0, 0);
Driver.Manage().Window.Size = new System.Drawing.Size(400, 680);