如标题所示,是如何自动关闭html未关闭的标签,很多时候我们在抓取html的时候碰到些奇葩的html抓取的时候有些标签是未关闭的,导致抓取html的时候出现抓取到的数据不是自己想要的,这时就需要对html的未关闭标签处理下,下面直接上这个封装好的方法:
[C#] 纯文本查看 复制代码 public static string AutoCloseHtmlTags(string inputHtml)
{
var regexStartTag = new Regex(@"<(!--\u002E\u002E\u002E--|!DOCTYPE|a|abbr|" +
@"acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|big" +
@"|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" +
@"command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|" +
@"figcaption|figure|font|footer|form|frame|frameset|h1> to <h6|head|" +
@"header|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|" +
@"map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|" +
@"output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|" +
@"source|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|" +
@"tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr)(\s\w+.*(\u0022|'))?>");
var startTagCollection = regexStartTag.Matches(inputHtml);
var regexCloseTag = new Regex(@"</(!--\u002E\u002E\u002E--|!DOCTYPE|a|abbr|" +
@"acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|" +
@"big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" +
@"command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|" +
@"figcaption|figure|font|footer|form|frame|frameset|h1> to <h6|head|header" +
@"|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|menu|" +
@"meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|" +
@"progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strike|" +
@"strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|" +
@"time|title|tr|track|tt|u|ul|var|video|wbr)>");
var closeTagCollection = regexCloseTag.Matches(inputHtml);
var startTagList = new List<string>();
var closeTagList = new List<string>();
var resultClose = "";
foreach (Match startTag in startTagCollection)
{
startTagList.Add(startTag.Value);
}
foreach (Match closeTag in closeTagCollection)
{
closeTagList.Add(closeTag.Value);
}
startTagList.Reverse();
for (int i = 0; i < closeTagList.Count; i++)
{
if (startTagList[i] != closeTagList[i])
{
int indexOfSpace = startTagList[i].IndexOf(
" ", System.StringComparison.Ordinal);
if (startTagList[i].Contains(" "))
{
startTagList[i].Remove(indexOfSpace);
}
startTagList[i] = startTagList[i].Replace("<", "</");
resultClose += startTagList[i] + ">";
resultClose = resultClose.Replace(">>", ">");
}
}
return inputHtml + resultClose;
}
希望对一些在抓取方面的基友有帮助。
以上内容来自projectcode,如有问题请联系论坛坛主
|