logo

如何在 C# 中使用Undetected ChromeDriver

2024-06-24 13:36
本文介绍了C# 中使用Undetected ChromeDriver的流程方式

集蜂云是一个可以让开发者在上面构建、部署、运行、发布采集器的数据采集云平台。加入到数百名开发者中,将你的采集器发布到市场,从而给你带来被动收入吧!

如果您曾在C#中使用Selenium进行网页抓取,您可能已经了解到网站很容易检测到这类自动化工具。然而,通过使用C#中的Undetected Chromedriver,您可以有效地规避这些检测措施,从而避免被网站阻止。

通常,Undetected Chromedriver是一个Python模块,但是在这篇指南中,您将学习如何在C#脚本中集成它。我们还将探讨一些常见问题及其解决方法,确保您能够顺利地执行Web自动化任务。

这样的优化不仅能够提高您的抓取效率,还能降低被反机器人系统检测到的风险,使得您的网页抓取工作更为可靠和稳定。

为什么在 C# 中使用Undetected ChromeDriver?

Undetected Chromedriver是对Selenium Chromedriver的优化版本,旨在避免被反机器人系统标记和阻止。

许多使用Selenium的网站通常会检测一些特定的变量,如包含"webdriver"和"document"的变量,这些变量通常以cdc_和wdc_开头。这些属性是标准Chromedriver的固有属性,使得网站能够相对容易地识别并标记您的脚本为可疑活动。

相比之下,Undetected Chromedriver修复了这些属性,优化了标准Chromedriver的实现方式,因此网络服务器更难检测到任何自动化的迹象。

这种优化不仅提升了脚本的安全性和稳定性,还显著降低了被反机器人系统拦截的风险,使得您能够更加可靠地执行自动化任务。

如何在 C# 中使用 ChromeDriver

本教程将指导您在C#项目中使用ChromeDriver,涵盖专用的C#库以及Python脚本的集成,以有效增强您的Web自动化任务能力。

选项 1:专用 C# 库

这些专用的C#库(例如Selenium.WebDriver.UndetectedChromeDriver和Selenium.UndetectedChromeDriver)为您提供了直接的解决方案。这些Undetected Chromedriver的实现允许您在C#脚本中利用Python模块的功能,无需编写任何Python代码。

我们将使用Selenium.UndetectedChromeDriver作为此示例,因为它是最受欢迎的。

首先,使用以下命令安装 C# 库。

PM> Install-Package Selenium.UndetectedChromeDriver

请注意,此命令适用于与Visual Studio中的包管理器控制台一起使用,或者您可以使用.NET CLI来安装包,如以下命令所示。

dotnet add package Selenium.UndetectedChromeDriver

之后,将该库作为依赖项包含在内,创建一个新的Undetected Chromedriver 实例。

using SeleniumUndetectedChromeDriver;
 
using (var driver = UndetectedChromeDriver.Create(driverExecutablePath: await new ChromeDriverInstaller().Auto()))
{
 
 
 
}

此库会自动下载适合您的Chrome浏览器版本的Selenium.UndetectedChromedriver驱动程序。同时,C#库会修补所有必要的属性,以避免被检测到。 接下来,您可以使用驱动程序实例导航到目标网站并检索所需的信息。在这个例子中,我们将抓取NowSecure,这是一个受Cloudflare保护的测试网站。

    // Navigate to the website
    driver.GoToUrl("https://nowsecure.nl"); 
 
    // Get the HTML content
    var htmlContent = driver.ExecuteScript("return document.documentElement.outerHTML;") as string;
 
    // Print the HTML content
    Console.WriteLine($"HTML Content:\n{htmlContent}");
 
}

完整代码如下:

using SeleniumUndetectedChromeDriver;
 
class Program
{
    static async Task Main()
    {
        using (var driver = UndetectedChromeDriver.Create(driverExecutablePath: await new ChromeDriverInstaller().Auto()))
        {
            // Navigate to the website
            driver.GoToUrl("https://nowsecure.nl");
 
            // Get the HTML content 
            var htmlContent = driver.ExecuteScript("return document.documentElement.outerHTML;") as string;
 
            // Print the HTML content
            Console.WriteLine($"HTML Content:\n{htmlContent}");
        }
    }
}

需要注意的是,这些是非官方的C# API,可能没有像Python模块那样经过广泛测试。因此,您可能偶尔会遇到不完全支持的限制或依赖项。

选项 2:Python 和 C# 集成方法

在C#中使用Undetected Chromedriver的另一种方法是编写Python自动化脚本,并从C#代码中调用该脚本。 由于该工具主要面向Python开发,这种方法使您能够访问其完整的功能集,包括最初由Undetected Chromedriver提供的更新。 此外,Python拥有丰富的网页抓取和自动化生态系统,其中包含大量库和工具。通过使用Python代码,您可以充分利用这一广泛的生态系统。 然而,C#和Python之间的跨语言通信需要额外的协调和数据交换,这增加了一些复杂性。确保确保这两种语言之间的工作流程顺畅是至关重要的。 接下来,让我们看看如何将Python集成到您的C#项目中。 首先,请确保您的机器上已经安装了Python。然后,使用以下命令安装Python的Undetected Chromedriver。

pip install undetected-chromedriver

接下来,创建一个Python脚本,使用Undetected Chromedriver访问目标网站。这种方法类似于使用专用的C#库。首先导入必要的依赖项,然后创建Undetected Chromedriver的实例,并导航到目标网站。在这个例子中,我们将捕获页面的屏幕截图。

import undetected_chromedriver as uc
 
# create an instance of the undetected ChromeDriver in headless mode
options = uc.ChromeOptions()
options.add_argument("--headless")
 
driver = uc.Chrome(options=options)
 
# navigate to target website
driver.get("https://www.nowsecure.nl")
 
# take a screenshot
driver.save_screenshot("screenshot.png")
 
print ("Screenshot taken")
 
# close the browser
driver.quit()

将上述脚本保存为Python文件,例如script.py。

现在,您可以在C#中调用这个Python脚本。

为了实现这一点,您需要使用System.Diagnostics命名空间内的Process类。该类提供了在C#应用程序中与外部程序(如Python脚本)进行交互的方法。

首先,导入命名空间并创建一个进程对象。以下是如何在C#中实现:

using System.Diagnostics;
 
using (Process process = new Process())
{
    // ...
 
}

在对象内,将 Python 解释器设置为文件名,并将 Python 脚本的路径指定为参数。

//..
{
    process.StartInfo.FileName = "python";
    process.StartInfo.Arguments = "C:\\Path\\to\\your\\script.py";
 
    //..
 
}

确保在系统的PATH中包含了Python或者提供Python可执行文件的完整路径。 接下来,配置进程启动信息。

//..
 
{
    process.StartInfo.UseShellExecute = false; // Don't use the operating system shell
    process.StartInfo.RedirectStandardOutput = true; // Redirect standard output
    process.StartInfo.CreateNoWindow = true; // Don't create a window for the process
    
    //..
}

这些配置确保了C#程序能够捕获Python脚本的输出。 最后,启动进程,读取标准输出,等待进程退出,并处理结果。

//..
 
{
    //..
 
    // start the process
    process.Start();
 
    // read the standard output
    string output = process.StandardOutput.ReadToEnd();
 
    // wait for the process to exit
    process.WaitForExit();
 
    // process the output 
    Console.WriteLine(output);
}

完整代码如下:

using System.Diagnostics;
 
class Program
{
    static void Main()
    {
        // Create a Process object
        using (Process process = new Process())
        {
            // Set the Python interpreter as the filename
            process.StartInfo.FileName = "python";
 
            // Specify the path to your Python script as arguments
            process.StartInfo.Arguments = "C:\\Path\\to\\your\\script.py";
 
            // Configure process settings
            process.StartInfo.UseShellExecute = false; // Don't use the operating system shell
            process.StartInfo.RedirectStandardOutput = true; // Redirect standard output
            process.StartInfo.CreateNoWindow = true; // Don't create a window for the process
 
            // Start the process
            process.Start();
 
            // Read the standard output
            string output = process.StandardOutput.ReadToEnd();
 
            // Wait for the process to exit
            process.WaitForExit();
 
            // Process the output
            Console.WriteLine(output);
        }
    }
}

运行它,你的结果应该是你的 Python 脚本的屏幕截图。

解决常见问题

虽然将Undetected Chromedriver集成到C#中可以增强网页抓取功能,但无论选择哪种方法,都可能会遇到特定的挑战。以下是一些常见问题及其可能的解决方案。

专门针对 C# 库的问题

这种方法的一个常见挑战是,C#库版本和浏览器更新之间可能存在不兼容的问题。因为这些库是Python模块的非官方移植,所以它们可能不会主动更新或维护,以支持浏览器更新中引入的最新变更。 这种不兼容性可能最终导致脚本错误。因此,在更新浏览器至最新版本之前,请确保它与当前使用的C#库兼容。

跨语言整合问题

将Python集成到C#脚本中可能会面临调试和代码维护方面的挑战。这些挑战源于传统调试工具和技术可能只能无缝处理某些Python和C#语言。 此外,管理跨语言错误可能会变得复杂。当错误从一种语言传播到另一种语言时,识别根本原因并实施有效的错误处理机制至关重要。 建议考虑使用支持Python和C#集成调试的工具来应对这些挑战。一些现代集成开发环境(IDE)提供了全面的多语言项目调试功能,能够有效跟踪Python和C#代码。 此外,请确保在Python和C#组件中采用一致的错误处理策略,并建立清晰的错误报告通信协议以处理两种语言之间的错误。

使用 C# 中Undetected ChromeDriver 的反检测技术

为了在C#中有效地使用Undetected Chromedriver,您可以采用反检测技术来规避阻止。

一种选择是随机化User-Agent字符串。通过修改脚本中的用户代理字符串,可以避免被已知的反机器人系统检测为自动化工具。这使得脚本发起的Web请求更难预测和识别。

另一个流行的选择是使用代理轮换。通过交替使用不同的IP地址和位置,可以避免IP跟踪和封禁,从而更轻松地进行数据抓取。

结论

在C#中使用Undetected Chromedriver面临着一系列独特的挑战。本指南探讨了多种在C#中使用Undetected Chromedriver的方法,包括集成Python和C#所涉及的复杂性。 尽管Undetected Chromedriver功能强大,但仍有可能被先进的反机器人系统所阻止。

集蜂云是一个可以让开发者在上面构建、部署、运行、发布采集器的数据采集云平台。平台提供了海量任务调度、三方应用集成、数据存储、监控告警、运行日志查看等功能,能够提供稳定的数据采集环境。平台提供丰富的采集模板,简单配置就可以直接运行,快来试一下吧。

导航目录