c#HtmlAgility Pack-无法获取图像src
我正在尝试学习如何从一个URL获取所有img src。但是,我的代码中的c#HtmlAgility Pack-无法获取图像src,c#,html-agility-pack,C#,Html Agility Pack,我正在尝试学习如何从一个URL获取所有img src。但是,我的代码中的imgs变量总是null。我做错了什么 static void Main(string[] args) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml("http://archive.ncsa.illinois.edu/primer.html"); HtmlAgilityPack
imgs
变量总是null
。我做错了什么
static void Main(string[] args)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml("http://archive.ncsa.illinois.edu/primer.html");
HtmlAgilityPack.HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img");
if (imgs != null)
{
foreach (HtmlAgilityPack.HtmlNode img in imgs)
{
string imgSrc = img.Attributes["src"].Value;
}
}
Console.ReadKey();
}
您使用的是HtmlDocument.LoadHtml,它的设计目的是获取html源代码,而不是url 您可以使用WebClient获取html,例如
WebClient wc = new WebClient();
string html = wc.DownloadString("http://archive.ncsa.illinois.edu/primer.html");
doc.LoadHtml(html);
HtmlDocument还支持加载,允许从各种其他来源加载内容。您使用的是HtmlDocument.LoadHtml,它旨在获取html源而不是url 您可以使用WebClient获取html,例如
WebClient wc = new WebClient();
string html = wc.DownloadString("http://archive.ncsa.illinois.edu/primer.html");
doc.LoadHtml(html);
HtmlDocument还支持允许从各种其他来源加载内容的加载。您确定它为空吗?您不需要对src属性执行任何操作。尝试打印它:
Console.WriteLine(imgSrc)代码>。是的,为什么我确定它为null是因为,当我调试时,它甚至不在“if(imgs!=null)”中。它跳过行“if(imgs!=null)”并转到Console.ReadKey();马上!你确定它是空的吗?您不需要对src属性执行任何操作。尝试打印它:Console.WriteLine(imgSrc)代码>。是的,为什么我确定它为null是因为,当我调试时,它甚至不在“if(imgs!=null)”中。它跳过行“if(imgs!=null)”并转到Console.ReadKey();马上!