Html agility pack not loading url

ε祈祈猫儿з 提交于 2019-12-23 11:13:13

问题


I have something like this:

class MyTask
{
    public MyTask(int id)
    {
        Id = id;
        IsBusy = false;
        Document = new HtmlDocument();
    }

    public HtmlDocument Document { get; set; }
    public int Id { get; set; }
    public bool IsBusy { get; set; }
}

class Program
{
    public static void Main()
    {
        var task = new MyTask(1);
        task.Document.LoadHtml("http://urltomysite");
        if (task.Document.DocumentNode.SelectNodes("//span[@class='some-class']").Count == 0)
        {
            task.IsBusy = false;
            return;
        }   
    }
}

Now when I start my program, it throws an error on the if sttement, saying that Object reference not set to an instance of an object.. Why isn't it loading my page? What am I doing wrong here?


回答1:


You are looking for .Load().

.LoadHtml() expects to be given physical HTML. You are giving a website to go to:

HtmlWeb website = new HtmlWeb();
HtmlDocument rootDocument = website.Load("http://www.example.com");



回答2:


In addition to Arran's answer

If .SelectNodes("//span[@class='some-class']") doesn't return any nodes and is null then doing a Count on it will give this exception.

Try

if (task.Document.DocumentNode.SelectNodes("//span[@class='some-class']") != null && 
    task.Document.DocumentNode.SelectNodes("//span[@class='some-class']").Count == 0)
    {
        task.IsBusy = false;
        return;
    }   


来源:https://stackoverflow.com/questions/19793291/html-agility-pack-not-loading-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!