2011-01-29 132 views
7

我想使用HTML敏捷包来解析HTML页面中的图片和href链接,但我对XML或XPath知之甚少。尽管在许多网站上查找帮助文档,但我无法解决问题。此外,我在VisualStudio 2005中使用C#,而且我不能流利地说英文,所以,我会衷心感谢能写出一些有用的代码。如何使用Html Agility Pack获取img/src或a/hrefs?

+0

而且,可以Html敏捷包解决相对路径? – iShow 2011-01-29 08:30:22

回答

21

主页上的​​做一些非常相似,但考虑:

HtmlDocument doc = new HtmlDocument(); 
doc.Load("file.htm"); // would need doc.LoadHtml(htmlSource) if it is not a file 
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"]) 
{ 
    string href = link["href"].Value; 
    // store href somewhere 
} 

所以你可以想象,对于IMG SRC @,只需更换每个aimg,并且hrefsrc。 你甚至可以简化为:

foreach(HtmlNode node in doc.DocumentElement 
       .SelectNodes("//a/@href | //img/@src") 
{ 
    list.Add(node.Value); 
} 

相对URL处理,看看Uri类。

+0

非常感谢!这是我第一次询问经验 – iShow 2011-01-29 11:12:03

6

该示例和接受的答案是错误的。它不会用最新版本进行编译。我尝试别的:

private List<string> ParseLinks(string html) 
    { 
     var doc = new HtmlDocument(); 
     doc.LoadHtml(html); 
     var nodes = doc.DocumentNode.SelectNodes("//a[@href]"); 
     return nodes == null ? new List<string>() : nodes.ToList().ConvertAll(
       r => r.Attributes.ToList().ConvertAll(
       i => i.Value)).SelectMany(j => j).ToList(); 
    } 

这对我有用。

1

也许我太迟了,在这里发表一个答案。以下为我工作:

var MainImageString = MainImageNode.Attributes.Where(i=> i.Name=="src").FirstOrDefault(); 
相关问题