给梦一个奔跑的方向!
PDF Print E-mail
User Rating: / 0
PoorBest 
Written by xlingfairy
Monday, 25 January 2010 20:24
 对于抓取的网页数据,不规则的HTML着实让人头痛,在某些浏览器下,如果一个标签未关闭,会引起意想不到的错误.
 
PHP里, DOMDocument 有个 loadHTML 功能, 利用这个函数,可以分析不规则的HTML,并规则化.
http://my.dajiaozi.com/php/83-close-html-tag-by-domdocument.html
 
C# 里, XMLDocument 没有类似的功能,用正则表达式我也考虑过,但是要写出来个这样的东东,并不是一天两天的能完成的事. 我也试着用 Winista.Text.HtmlParser 这个东东,但是试验得知:容错特别差(可能是我不会用,也可能是版本太低了吧)!
在网上找了几个,感觉只有这个还好点,容错特别强, HtmlAgilityPack:
http://htmlagilitypack.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=33903
 
下面的这段:
 
'<a href=aa.html id="abc" />abc</a><img src='img.gif'>abc<div><span><div>
 
能转成:
 
'<a href="/aa.html" id="abc"></a>abc<img src='img.gif' />abc<div><span><div></div></span></div>
 
太完美了。
用法也很简单:
 
        public static string CloseHTMLTag( this string ctx) {
            if (string.IsNullOrEmpty(ctx))
                return ctx;
            HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
            html.LoadHtml("<l>" + ctx + "</l>");
            html.OptionOutputOptimizeAttributeValues = false;
            html.OptionOutputAsXml = true;
            return html.DocumentNode.FirstChild.InnerHtml;
        }
 

Add comment


Security code
Refresh

Popular Contents

Recommend

Site Info

Members : 1
Content : 100
Web Links : 7
Content View Hits : 56176

Links