2017-05-27 80 views
0

基于之前编写的code snippet,我现在试图将多个图像从某个subreddit一次存储到本地目录中。我的问题是,我无法让我的LINQ语句正常工作。我也不想下载缩略图这就是为什么我看了看在HTML页面和发现,我的目标是获取链接隐藏在5级href属性中:LINQ中的System.NullReferenceException

(...) 
Level 1: <div class="content">...</div> 
    Level 2: <div class="spacer">...</div> 
     Level 3: <div class="siteTable">...</div> 
      Level 4: <div class=" thing id-t3_6dj7qp odd link ">...</div>      
       Level 5: <a class="thumbnail may-blank outbound" href="href="http://i.imgur.com/jZ2ZAyk.jpg"">...</a> 

这是符合我最好的选择“???”:

.Where(link => Directory.GetParent(link).Equals(@"http://i.imgur.com")) 

可悲的是它抛出一个error指出

Object reference not set to an instance of an object 

现在好了,我知道为什么它不是w ^但我仍然不知道如何重写这一行,因为我对Lambda表达式还是比较新的。说实话,我真的不知道为什么我第一次得到System.NullReferenceException,但不是在下一行。有什么不同?也许我在这个问题上的做法甚至不是很好的做法,所以请让我知道我可以如何继续下去。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.IO; 
using System.Net; 
using HtmlAgilityPack; 

namespace GetAllImages 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<string> imageLinks = new List<string>(); 

      // Specify Directory manually 
      string dirName = "Jessica Clements"; 
      string rootPath = @"C:\Users\Stefan\Desktop"; 
      string dirPath = Path.Combine(rootPath, dirName); 

      // Specify the subReddit manually 
      string subReddit = "r/Jessica_Clements"; 
      string url = @"https://www.reddit.com/" + subReddit; 

      try 
      { 
       DirectoryInfo imageFolder = Directory.CreateDirectory(dirPath);     

       HtmlDocument document = new HtmlWeb().Load(url); 
       imageLinks = document.DocumentNode.Descendants("a") 
          .Select(element => element.GetAttributeValue("href", null)) 
          .Where(???) 
          .Where(stringLink => !String.IsNullOrEmpty(stringLink)) 
          .ToList(); 

       foreach(string link in imageLinks) 
       { 
        using (WebClient _wc = new WebClient()) 
        { 
         _wc.DownloadFileAsync(new Uri(link), Path.Combine(dirPath, Path.GetFileName(link))); 
        }       
       } 

      Console.WriteLine($"Files successfully saved in '{Path.GetFileName(dirPath)}'.");    

      } 

      catch(Exception e) 
      { 
       while(e != null) 
       { 
        Console.WriteLine(e.Message); 
        e = e.InnerException; 
       } 
      } 

      if(System.Diagnostics.Debugger.IsAttached) 
      { 
       Console.WriteLine("Press any key to continue . . ."); 
       Console.ReadKey(true); 
      } 
     } 
    } 
} 

编辑:万一有人有兴趣在此解决方案,就是我做它到底使用下面的答案的工作:

HtmlDocument document = new HtmlWeb().Load(url); 
imageLinks = document.DocumentNode.Descendants("a") 
      .Select(element => element.GetAttributeValue("href", null)) 
      .Where(link => (link?.Contains(@"http://i.imgur.com") == true)) 
      .Distinct() 
      .ToList(); 
+0

更好的方法,您的问题是使用[JSON API(https://开头WWW。 reddit.com/r/Jessica_Clements/.json)而不是解析HTML。 – Nasreddine

回答

2

鉴于此行抛出异常:

.Where(link => Directory.GetParent(link).Equals(@"http://i.imgur.com")) 

我会确保link不为空,并且GetParent(link)的结果也不为空。所以,你可以这样做:

.Where(link => link != null && (Directory.GetParent(link)?.Equals(@"http://i.imgur.com") ?? false)) 

通知空校验和GetParent()?.。如果从GetParent()返回null,则停止该术语的执行。它被称为Null Conditional Operator或“猫王操作员”,因为它可以被看作是双眼三头发。如果执行因空值而停止,则?? false将给出默认值。

但是,如果你打算解析HTML代码,你一定要看看Html Agility Pack (HAP)

+0

我有一个新想法:我如何交换两个Where语句?那样我不能确保这个链接不可能是空的?我现在是移动的,所以我不能检查是否是真的。 – Stefan

+0

是的,完全正确。跳过空检查然后去elvis操作员。或者,使用'String.Equals(link,“...”)'。通过不使用变量'link'来调用方法,你不能运行NullRefs – Waescher

1

,如果你想获得的所有链接指向http://i.imgur.com,你需要像这样

imageLinks = document.DocumentNode.Descendants("a") 
       .Select(element => element.GetAttributeValue("href", null)) 
       .Where(link => link?.Contains(@"http://i.imgur.com") == true) 
       .ToList(); 
相关问题