基于之前编写的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();
更好的方法,您的问题是使用[JSON API(https://开头WWW。 reddit.com/r/Jessica_Clements/.json)而不是解析HTML。 – Nasreddine