3

HtmlAgilityPack中使用xpath获取属性值 - jvx

 2 years ago
source link: https://www.cnblogs.com/j4587698/p/16521268.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

HtmlAgilityPack介绍

HtmlAgilityPack是一个专门用来解析Html的库,它可以使用xml的方式来解析html。

有人说了,html本身不就是xml?是的,html就是xml,但是html很宽松,没有关闭的节点也可以用,还有一些其他的内容比如js夹杂在里面。如果直接使用xml解析库的话9成会报错的。

而HtmlAgilityPack会去处理这些问题,把Html转成一个接近标准的xml来供我们使用。

网上关于HtmlAgilityPack的介绍其实很多,而且用法其实就那么几句话。

var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var root = doc.DocumentNode;

这个也没啥好说的,主要就是doc.LoadHtml(html);这里有个重载是doc.Load(),里面可以直接放url,也可以放Stream

我们这里使用LoadHtml直接加载html内容主要是因为我们的html拿的时候可能还需要别的东西,需要另行获取。

最后的var root = doc.DocumentNode;这个root就是<html>节点,整个html的根目录。

然后很多文章的说法就是我们要获取Node,即使用

var node =root.SelectSingleNode("xpath");

这样肯定是没问题的,然后我们如果要获得它的属性,就可以拿这个Node的node.GetAttributeValue("name", 默认值);获取内容。

比如我们要获取idtesta标签的href,我们可以写个例子

            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var root = doc.DocumentNode;
            var node =root.SelectSingleNode("//a[@id='test']");
            var href = GetAttributeValue("href", ""); 

这样我们就能获取到href了。是不是很简单?

直接获取属性值

上面的例子看起来很好,但是有个比较麻烦的问题,就是有时候我们想直接获取属性值。比如我有一个这样的xpath //a[@id='test']/@href,如果我们还用上面的代码套进去。

            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var root = doc.DocumentNode;
            var node =root.SelectSingleNode("//a[@id='test']/@href");

我们的node是不是就是href的值呢?经过测试,不是的,这里的node还是那个a。

所以我们无法直接这样来获取。

经过一番查询,发现HtmlAgilityPack提供了一个HtmlNodeNavigator来完成这个需求。

var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var root = doc.DocumentNode;
            HtmlNodeNavigator navigator = (HtmlNodeNavigator)root.CreateNavigator();
            var node = navigator.SelectSingleNode("//a[@id='test']/@href");
            var href = node.Value;

这里我们可以获取到一个HtmlNodeNavigator的node,这个node不是指向a标签,而是直接指向href属性,所以我们直接拿node.Value就可以获取到真正的href的值了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK