我有一个语法不正确的 HTML 文件,我正在用 HTML Agility Pack 解析它.
但是如果我有一个像
这样的链接 <a href="http://google.com/!/!!!">Google</a>
这是一个问题,有没有一种可能的方法来检测损坏的链接,以便在发现错误时(该链接上没有可用页面)应用程序将该链接存储在列表中并返回它?
同样的标签问题,例子:
<img hhh="jjj"/>
这里图片标签全错了,这个也应该在'errors for repair'列表中。
提前致谢。
最佳答案
你需要遍历Document.DocumentNode.Descendants("a")
并检查是否href
标签有问题。
同样,你可以遍历Document.DocumentNode.Descendants("img")
并检查 src
属性。
编辑:
要检查不良属性,您可以维护一个 Dictionary<string, IEnumerable<string>>
将标记名称映射到有效属性,然后使用 LINQ 查找缺失的属性,如下所示:
from tag in Document.DocumentNode.Descendants()
let legalAttributes = allAttributes[tag.TagName]
from attribute in tag.Attributes
where !legalAttributes.Contains(attribute.Name, StringComparer.OrdinalIgnoreCase)
select new { Tag = tag.OuterHtml, Attribute = attribute.Name }
关于c# - 使用 C#,如何检测断开的链接或标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3863483/