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

C#中Selenium IWebDriver未正确赋值导致NullReferenceException

问题核心

你只在类级别声明了IWebDriver bot,但没有实例化这个对象,导致调用bot.Navigate()时它是null,触发空引用异常。

正确实现方式

1. 类级声明并封装IWebDriver

建议用私有字段(别用public,保证封装性),避免外部随意修改。

2. 在登录方法中实例化IWebDriver

确保UserLogin方法执行时,先创建IWebDriver的实例,再执行登录逻辑。

3. 调用顺序保证

在DataGrabber中先调用UserLogin,确保IWebDriver已经被正确初始化。

完整代码示例
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

public class WebScraper
{
    // 类级别私有字段,封装WebDriver实例
    private IWebDriver _bot;

    public void UserLogin()
    {
        // 实例化ChromeDriver(根据你用的浏览器替换,比如FirefoxDriver)
        _bot = new ChromeDriver();
        _bot.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
        
        // 执行登录流程
        _bot.Navigate().GoToUrl("https://your-login-page.com");
        _bot.FindElement(By.Id("username")).SendKeys("your-username");
        _bot.FindElement(By.Id("password")).SendKeys("your-password");
        _bot.FindElement(By.CssSelector("button[type='submit']")).Click();
    }

    public void DataGrabber()
    {
        // 先执行登录,确保_bot已实例化
        UserLogin();
        
        // 现在可以正常使用_bot导航和操作
        _bot.Navigate().GoToUrl("https://your-data-page.com");
        
        // 后续数据抓取逻辑...
        var dataElement = _bot.FindElement(By.Id("target-data"));
        Console.WriteLine(dataElement.Text);
        
        // 使用完毕记得释放资源,避免浏览器进程残留
        _bot.Quit();
        _bot.Dispose();
    }
}
额外注意点
  • 避免重复实例化:如果UserLogin可能被多次调用,先判断_bot是否为null,再实例化:
    public void UserLogin()
    {
        if (_bot == null)
        {
            _bot = new ChromeDriver();
            _bot.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
        }
        // 登录逻辑...
    }
    
  • 资源释放:必须调用Quit()和Dispose()关闭浏览器,否则会残留后台进程。可以实现IDisposable接口来规范资源管理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:42:32