[英]System.NullReferenceException in LINQ
根據先前的書面代碼片段,我現在嘗試一次將某個特定子目錄中的多個圖像存儲到本地目錄中。 我的問題是我無法使我的LINQ語句正常工作。 我也不想下載縮略圖,這就是為什么我看一下HTML頁面並發現我要檢索的鏈接隱藏在href
屬性的5級中的原因:
(...)
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"))
可悲的是它拋出了一個錯誤,指出
Object reference not set to an instance of an object
現在好了,我知道為什么它行不通了,但是我仍然不知道如何重寫這一行,因為我對Lambda Expressions還是很陌生。 老實說,我真的不知道為什么我首先獲得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();
鑒於此行引發異常:
.Where(link => Directory.GetParent(link).Equals(@"http://i.imgur.com"))
我將確保該link
不為null,並且GetParent(link)
的結果也不為null。 因此,您可以執行以下操作:
.Where(link => link != null && (Directory.GetParent(link)?.Equals(@"http://i.imgur.com") ?? false))
注意空檢查和?.
在GetParent()
。 如果從GetParent()
返回null,則此操作將停止執行該術語。 之所以稱其為“ 空條件運算符”或“ Elvis運算符”,是因為它可以看成是兩根頭發扭曲的眼睛。 ?? false
如果由於空值而停止執行,則?? false
給出默認值。
但是 ,如果您打算解析HTML代碼,則絕對應該看看Html Agility Pack(HAP) 。
如果您嘗試獲取指向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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.