我有一个代码,可以在网页上搜寻所有PDF文件并将其下载到文件夹中。但是现在它开始丢弃错误:
System.NullReferenceException HResult = 0x80004003消息=对象引用未设置为对象的实例。来源=西北履带StackTrace:位于NW_Crawler.Program.Main(String [] args)中C:\ Users \ PC \ source \ repos \ NW Crawler \ NW Crawler \ Program.cs:第16行
指向ProductListPage
中的foreach (HtmlNode src in ProductListPage)
关于如何解决此问题,是否有任何提示?我试图实现异步/等待,但没有成功。也许我在做错什么事...
这里是要完成的过程:
https://www.nordicwater.com/products/waste-water/
<a class="ap-area-link" href="https://www.nordicwater.com/product/mrs-meva-multi-rake-screen/">MRS MEVA multi rake screen</a>
进入每个链接并搜索PDF文件。 PDF文件位于:
<div class="dl-items">
<a href="https://www.nordicwater.com/wp-content/uploads/2016/04/S1126-MRS-brochure-EN.pdf" download="">
这是我的完整测试代码:
using HtmlAgilityPack;
using System;
using System.Net;
namespace NW_Crawler
{
class Program
{
static void Main(string[] args)
{
{
HtmlDocument htmlDoc = new HtmlWeb().Load("https://www.nordicwater.com/products/waste-water/");
HtmlNodeCollection ProductListPage = htmlDoc.DocumentNode.SelectNodes("//a[@class='ap-area-link']//a");
Console.WriteLine("Here are the links:" + ProductListPage);
foreach (HtmlNode src in ProductListPage)
{
htmlDoc = new HtmlWeb().Load(src.Attributes["href"].Value);
// Thread.Sleep(5000); // wait some time
HtmlNodeCollection LinkTester = htmlDoc.DocumentNode.SelectNodes("//div[@class='dl-items']//a");
if (LinkTester != null)
{
foreach (var dllink in LinkTester)
{
string LinkURL = dllink.Attributes["href"].Value;
Console.WriteLine(LinkURL);
string ExtractFilename = LinkURL.Substring(LinkURL.LastIndexOf("/"));
var DLClient = new WebClient();
// Thread.Sleep(5000); // wait some time
DLClient.DownloadFileAsync(new Uri(LinkURL), @"C:\temp\" + ExtractFilename);
}
}
}
}
}
}
}
进行了一些更改以覆盖您可能会看到的错误。
更改
src.GetAttributeValue("href", string.Empty)
代替src.Attribute["href"].Value;
。如果href不存在或为null,则将获得“对象引用未设置为对象的实例”ProductListPage
是否有效且不为null。 ExtractFileName
在名称中包含/。您想在子字符串方法中使用+ 1来跳过“最后一个/从索引的开始”。//a[@class='ap-area-link']
更改为//a[@class='ap-area-link']//a
。您正在<a>
标签中搜索<a>
,该标签为null。不过,如果您要以这种方式查询它,则第一个IF语句将检查ProductListPage != null
是否会处理错误。 HtmlDocument htmlDoc = new HtmlWeb().Load("https://www.nordicwater.com/products/waste-water/");
HtmlNodeCollection ProductListPage = htmlDoc.DocumentNode.SelectNodes("//a[@class='ap-area-link']");
if (ProductListPage != null)
foreach (HtmlNode src in ProductListPage)
{
string href = src.GetAttributeValue("href", string.Empty);
if (string.IsNullOrEmpty(href))
continue;
htmlDoc = new HtmlWeb().Load(href);
HtmlNodeCollection LinkTester = htmlDoc.DocumentNode.SelectNodes("//div[@class='dl-items']//a");
if (LinkTester != null)
foreach (var dllink in LinkTester)
{
string LinkURL = dllink.GetAttributeValue("href", string.Empty);
if (string.IsNullOrEmpty(LinkURL))
continue;
string ExtractFilename = LinkURL.Substring(LinkURL.LastIndexOf("/") + 1);
new WebClient().DownloadFileAsync(new Uri(LinkURL), @"C:\temp\" + ExtractFilename);
}
}