如何在 C# 中禁用 ChromeDriver Selenium 中的 WEB USB 标志?

问题描述 投票:0回答:1

错误:

[3528:3760:0205/072321.889:ERROR:device_event_log_impl.cc(192)] [07:23:21.489] USB: usb_service_win.cc:105  SetupDiGetDeviceProperty({{A45C254E-DF1C-4EFD-8020-67D146A850E0}, 6}) failed: Element not found. (0x490)

我在 AWS EC2 实例中运行我的应用程序,在本地它运行良好,但在服务器中运行不佳。

我在控制台中遇到上述错误作为日志,而我的应用程序此时陷入困境。

Dictionary<string, object> prefs = new Dictionary<string, object>
            {
                { "webusb_allow_devices", false }

            };

            browserOptions.AddAdditionalCapability("prefs", prefs);

如果我使用首选项,它会给出类似的错误 已经有一个首选项功能的选项。

然后我尝试了这个

Dictionary<string, object> prefs = new Dictionary<string, object>
            {
                { "webusb_allow_devices", false }

            };

            browserOptions.AddAdditionalCapability("chromeOptions", prefs);

然后我得到了这个错误:

OpenQA.Selenium.WebDriverException: unknown error: cannot parse capability: goog:chromeOptions

c# amazon-web-services web-scraping selenium-chromedriver web-crawler
1个回答
0
投票

分析您的错误代码,错误表明在尝试添加 “prefs” 功能时已经有 “prefs” 功能的选项,这表明 “prefs” 功能可能已在其他位置设置您的代码,或者这不是修改 Selenium 设置中的 Chrome 选项的正确方法。

因此,您可以使用 "chromeOptions" 功能直接添加 Chrome 选项,而不是尝试通过 "prefs" 功能添加它们。以下示例展示了如何修改代码并使用 "chromeOptions":

// Create a ChromeOptions instance
ChromeOptions options = new ChromeOptions();

// Add the '--disable-webusb' argument directly to the Chrome options
options.AddArgument("--disable-webusb");

// Pass the Chrome options to the browser options
browserOptions.AddAdditionalCapability("chromeOptions", options);

通过直接将 --disable-webusb 参数添加到 Chrome 选项并使用 "chromeOptions" 功能传递它们,您应该能够在 ChromeDriver Selenium 中禁用 WEB USB 功能在 C# 中,没有遇到与 "prefs" 功能相关的错误。

另外,考虑设置 excludeSwitches 功能,它可能真正起作用,例如:

ChromeOptions options = new ChromeOptions();
        options.AddExcludedArgument("enable-features=WebUSB");

但是下面的方法要好得多:

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

class Program
{
    static void Main(string[] args)
    {
        // Step 1: Create Chrome options and add the --disable-webusb argument
        ChromeOptions options = new ChromeOptions();
        options.AddArgument("--disable-webusb");

        // Step 2: Create a Chrome driver instance with the Chrome options
        ChromeDriver driver = new ChromeDriver(options);

        // Now you can use the Chrome driver instance to interact with your application
        // For example, you can navigate to a URL:
        driver.Navigate().GoToUrl("https://example.com");

        // Remember to close the driver when you're done
        driver.Quit();
    }
}

这将确保 Chrome 选项正确配置为禁用 WEB USB 并传递到 ChromeDriver 实例,从而解决您遇到的问题。

© www.soinside.com 2019 - 2024. All rights reserved.