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

.NET Core+Selenium在Windows与CentOS运行异常问题求助

解决.NET Core + Selenium在CentOS下PageSource返回字典的问题

不用着急切换到Python技术栈,这个问题完全可以在.NET Core环境下解决!核心原因是CentOS上Chrome浏览器与ChromeDriver版本不匹配,或者环境配置缺失导致驱动交互异常,以下是具体的修复步骤:

1. 确保Chrome浏览器与ChromeDriver版本完全匹配

Selenium对浏览器和驱动的版本一致性要求极高,这是此类跨平台问题的最常见诱因:

  • 先在CentOS上安装官方稳定版Chrome:
    yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
    
  • 查看安装后的Chrome版本:
    google-chrome --version
    
  • 下载对应版本的ChromeDriver(必须和Chrome版本号完全一致,比如Chrome是118.x,就下载118.x的ChromeDriver),解压后放到你的/root目录,再赋予执行权限:
    chmod +x /root/chromedriver
    

2. 优化Selenium驱动配置

CentOS的无头环境需要额外的参数来规避系统限制,修改你的SetupTest2方法,补充必要配置并开启日志方便排查:

public static IWebDriver SetupTest2() {
    String driverPath = @"/root";
    String driverExecutableFileName = "chromedriver";
    ChromeOptions options = new ChromeOptions();
    // 补充无头模式必需的参数
    options.AddArgument("--headless=new"); // 新版无头模式,兼容性更强
    options.AddArgument("--no-sandbox");
    options.AddArgument("--disable-dev-shm-usage"); // 解决CentOS共享内存限制问题
    options.AddArgument("--disable-gpu");
    options.AddArgument("--window-size=1920,1080"); // 避免页面布局异常导致的源码获取失败

    ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverPath, driverExecutableFileName);
    // 开启日志,方便后续排查驱动交互问题
    service.LogPath = Path.Combine(driverPath, "chromedriver.log");
    service.EnableVerboseLogging = true;

    IWebDriver driver = new ChromeDriver(service, options, TimeSpan.FromSeconds(30));
    return driver;
}

3. 替代PageSource的获取方式

如果上述配置后仍有问题,可以绕过PageSource属性,直接获取页面根元素的HTML内容:

// 替换原来的Console.WriteLine(driver.PageSource);
var htmlRoot = driver.FindElement(By.TagName("html"));
Console.WriteLine(htmlRoot.GetAttribute("outerHTML"));

关于是否切换技术栈

完全没必要换Python!.NET Core的跨平台支持已经非常成熟,Selenium在Linux下的兼容性也很稳定,只要环境配置到位,和Windows下的运行表现是一致的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:52:51