我正在尝试从网站检索所有http和https链接,但有时我会得到null异常

时间:2012-05-16 10:50:25

标签: c# html-parsing html-agility-pack

public partial class Form1 : Form
{
   int y = 0;
   string url = @"http://www.google.co.il";
   string urls = @"http://www.bing.com/images/search?q=cat&go=&form=QB&qs=n";

   public Form1()
   {
       InitializeComponent();
       //webCrawler(urls, 3);
       List<string> a = webCrawler(urls, 1);
       //GetAllImages();
   }

   private int factorial(int n)
   {
      if (n == 0) return 1;
      else y = n * factorial(n - 1);
      listBox1.Items.Add(y);
      return y;
   }

   private List<string> getLinks(HtmlAgilityPack.HtmlDocument document)
   {
       List<string> mainLinks = new List<string>();

       if (document.DocumentNode.SelectNodes("//a[@href]") == null)
       { }

       foreach (HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
       {
           var href = link.Attributes["href"].Value;
           mainLinks.Add(href);
       }

       return mainLinks;
   }

   private List<string> webCrawler(string url, int levels)
   {
      HtmlAgilityPack.HtmlDocument doc;
      HtmlWeb hw = new HtmlWeb(); 

      List<string> webSites;// = new List<string>();
      List<string> csFiles = new List<string>();

      csFiles.Add("temp string to know that something is happening in level = " + levels.ToString());
      csFiles.Add("current site name in this level is : "+url);
      /* later should be replaced with real cs files .. cs files links..*/

      doc = hw.Load(url);
      webSites = getLinks(doc);

      if (levels == 0)
      {
         return csFiles;
      }
      else
      {
         int actual_sites = 0;

         for (int i = 0; i < webSites.Count() && i< 100000; i++) // limiting ourseleves for 20 sites for each level for now..
         //or it will take forever.
         {
             string t = webSites[i];
             /*
                    if (!webSites.Contains(t))
                    {
                        webCrawler(t, levels - 1);
                    }
             */

             if ( (t.StartsWith("http://")==true) || (t.StartsWith("https://")==true) ) // replace this with future FilterJunkLinks function
             {
                actual_sites++;
                csFiles.AddRange(webCrawler(t, levels - 1));
                richTextBox1.Text += t + Environment.NewLine;
             }
          }

          // report to a message box only at high levels..
          if (levels==1)
             MessageBox.Show(actual_sites.ToString());

          return csFiles;
       }                
    }

在将几个站点发送到getLinks函数后抛出异常。

例外是在该行的getLinks函数中:

foreach (HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
  

对象引用未设置为对象的实例

我试图在那里使用IF来检查它是否为null然后我做了return mainLinks;这是一个列表。

但如果我这样做,我就不会从网站上获得所有链接。

现在我在构造函数中使用url如果我正在使用url(www.google.co.il)我几秒后就会得到相同的异常。

我无法弄清楚为什么会抛出此异常。这个例外是否有任何原因?

  

System.NullReferenceException未处理
  Message =对象引用未设置为对象的实例   来源= GatherLinks
  堆栈跟踪:
  在D:\ C-Sharp \ GatherLinks \ GatherLinks \ GatherLinks \ Form1.cs中的GatherLinks.Form1.getLinks(HtmlDocument文档):第55行   at GatherLinks.Form1.webCrawler(String url,Int32 levels)在D:\ C-Sharp \ GatherLinks \ GatherLinks \ GatherLinks \ Form1.cs:第76行   at GatherLinks.Form1.webCrawler(String url,Int32 levels)在D:\ C-Sharp \ GatherLinks \ GatherLinks \ GatherLinks \ Form1.cs:第104行
  在D:\ C-Sharp \ GatherLinks \ GatherLinks \ GatherLinks \ Form1.cs中的GatherLinks.Form1..ctor():第29行   在D:\ C-Sharp \ GatherLinks \ GatherLinks \ GatherLinks \ Program.cs中的GatherLinks.Program.Main():第18行   在System.AppDomain._nExecuteAssembly(Assembly assembly,String [] args)
  在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)
  在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
  在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)
  在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)
  在System.Threading.ThreadHelper.ThreadStart()

1 个答案:

答案 0 :(得分:4)

问题似乎是你正在测试null,但后来什么也没做 - 这里

            if (document.DocumentNode.SelectNodes("//a[@href]") == null)
            {
            }

我怀疑你想要处理null case但是没有编写代码来执行它。你可能想要这样的东西:

    private List<string> getLinks(HtmlAgilityPack.HtmlDocument document)
        {
           List<string> mainLinks = new List<string>();
           if (document.DocumentNode.SelectNodes("//a[@href]") != null)
            {

                foreach (HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
                {
                    var href = link.Attributes["href"].Value;
                    mainLinks.Add(href);
                }
            }
            return mainLinks;
        }

你可能想要整理更像的东西:

   private List<string> getLinks(HtmlAgilityPack.HtmlDocument document)
        {
           List<string> mainLinks = new List<string>();
           var linkNodes = document.DocumentNode.SelectNodes("//a[@href]");
           if (linkNodes != null)
            {
                foreach (HtmlNode link in linkNodes)
                {
                    var href = link.Attributes["href"].Value;
                    mainLinks.Add(href);
                }
            }
            return mainLinks;
        }