HtmlAgilityPack HasAttribute?
我想做的就是
node.Attributes["class"].Value
但是如果节点没有class
属性,它就会崩溃。 所以,我必须首先检查它的存在,对吗? 我怎么做? Attributes
不是dict(它是一个包含内部字典的列表),并且没有HasAttribute方法(只是一个HasAttributes,它指示它是否具有任何属性)。 我该怎么办?
试试这个:
String val; if(node.Attributes["class"] != null) { val = node.Attributes["class"].Value; }
或者您可以添加此function
public static class HtmlAgilityExtender { public static String ValueOrDefault(this HtmlAttribute attr) { return (attr != null) ? attr.Value : String.Empty; } }
然后使用
node.Attributes["class"].ValueOrDefault();
我还没有测试过那个,但它应该可行。
请试试这个:
String abc = String.Empty; if (tag.Attributes.Contains(@"type")) { abc = tag.Attributes[@"type"].Value; }
此代码可用于获取两个脚本标记之间的所有文本。
String getURL(){ return @"some site address"; } List Internalscripts() { HtmlAgilityPack.HtmlDocument doc = new HtmlWeb().Load((@"" + getURL())); //Getting All the JavaScript in List HtmlNodeCollection javascripts = doc.DocumentNode.SelectNodes("//script"); List scriptTags = new List (); foreach (HtmlNode script in javascripts) { if(!script.Attributes.Contains(@"src")) { scriptTags.Add(script.InnerHtml); } } return scriptTags; }