可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
All I want to do is
node.Attributes["class"].Value
But if the node doesn't have the class
attribute, it crashes. So, I have to check for its existence first, right? How do I do that? Attributes
is not a dict (its a list that contains an internal dict??), and there's no HasAttribute method (just a HasAttributes which indicates if it has any attribute at all). What do I do?
回答1:
Try this:
String val; if(node.Attributes["class"] != null) { val = node.Attributes["class"].Value; }
Or you might be able to add this
public static class HtmlAgilityExtender { public static String ValueOrDefault(this HtmlAttribute attr) { return (attr != null) ? attr.Value : String.Empty; } }
And then use
node.Attributes["class"].ValueOrDefault();
I havent tested that one, but it should work.
回答2:
Please try this:
String abc = String.Empty; if (tag.Attributes.Contains(@"type")) { abc = tag.Attributes[@"type"].Value; }
回答3:
This Code Can Be Used to get all text between two script tags.
String getURL(){ return @"some site address"; } List<string> Internalscripts() { HtmlAgilityPack.HtmlDocument doc = new HtmlWeb().Load((@"" + getURL())); //Getting All the JavaScript in List HtmlNodeCollection javascripts = doc.DocumentNode.SelectNodes("//script"); List<string> scriptTags = new List<string>(); foreach (HtmlNode script in javascripts) { if(!script.Attributes.Contains(@"src")) { scriptTags.Add(script.InnerHtml); } } return scriptTags; }