在 C# 中解析 html 的最佳方法是什么?[关闭]

What is the best way to parse html in C#? [closed]

提问人:Luke 提问时间:9/11/2008 最后编辑:Charles StewartLuke 更新时间:6/10/2021 访问量:532747


答:

0赞 Corin Blaikie 9/11/2008 #1

您可以使用 HTML DTD 和通用 XML 解析库。

评论

8赞 Frank Krueger 9/11/2008
很少有实际的 HTML 页面能够在 XML 解析库中幸存下来。
1赞 Mark Ingram 9/11/2008 #2

解析 HTML 的问题在于它不是一门精确的科学。如果您要解析的是 XHTML,那么事情会容易得多(正如您提到的,您可以使用通用的 XML 解析器)。因为 HTML 不一定是格式良好的 XML,所以在尝试解析它时会遇到很多问题。它几乎需要逐个站点地完成。

评论

1赞 Pablo Fernandez 12/8/2009
解析 W3C 指定的格式良好的 HTML 难道不是一门与 XHTML 完全相同的科学吗?
0赞 Dominic K 2/16/2010
它应该是,但人们不这样做。
0赞 12/22/2010
@J. Pablo 虽然没有那么容易(因此也是图书馆:p的原因)......例如,在 HTML4/5 下不需要显式关闭标签。哎呀!<p>
27赞 Erlend 9/11/2008 #3

可以使用 TidyNet.Tidy 将 HTML 转换为 XHTML,然后使用 XML 分析器。

另一种选择是使用内置引擎 mshtml:

using mshtml;
...
object[] oPageText = { html };
HTMLDocument doc = new HTMLDocumentClass();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(oPageText);

这允许您使用类似 javascript 的函数,例如 getElementById()

评论

4赞 Alex Baranosky 1/9/2009
说我疯了,但我很难弄清楚如何使用 mshtml。你有什么好的链接吗?
1赞 Wilfred Knievel 1/13/2010
@Alex需要包含 Microsoft.mshtml 可以在此处找到更多信息:msdn.microsoft.com/en-us/library/aa290341(VS.71).aspx
0赞 JP Hellemons 10/25/2011
我有一篇关于 Tidy.Net 和 ManagedTidy 都能够解析和验证 (x)html 文件的博客文章。如果你不需要验证东西。我会选择htmlagilitypack。jphellemons.nl/post/......
3赞 Frank Krueger 9/11/2008 #4

我认为@Erlend的使用是最好的方法。但是,我也很幸运地使用了这个简单的库:HTMLDocument

Sgml阅读器

10赞 Alan 9/11/2008 #5

您可以在不疯狂的情况下做很多事情 第三方产品和 mshtml(即互操作)。使用 System.Windows.Forms.WebBrowser。从那里,您可以对 HtmlDocument 执行“GetElementById”或对 HtmlElements 执行“GetElementsByTagName”等操作。如果你想实际使用浏览器(例如模拟按钮点击),你可以使用一点反射(imo 比 Interop 更小的邪恶)来做到这一点:

var wb = new WebBrowser()

...告诉浏览器导航(与此问题无关)。然后,在Document_Completed事件中,您可以像这样模拟点击。

var doc = wb.Browser.Document
var elem = doc.GetElementById(elementId);
object obj = elem.DomElement;
System.Reflection.MethodInfo mi = obj.GetType().GetMethod("click");
mi.Invoke(obj, new object[0]);

你可以做类似的反思来提交表格等。

享受。

1赞 Rahul 9/19/2008 #6

我过去曾使用 ZetaHtmlTidy 加载随机网站,然后使用 xpath 攻击内容的各个部分(例如 /html/body//p[@class='textblock'])。它运行良好,但有一些特殊的网站存在问题,所以我不知道这是否是绝对最好的解决方案。

137赞 Mark Cidade 9/19/2008 #7

Html 敏捷包

这是一个敏捷的 HTML 解析器,它构建了一个读/写 DOM 并支持普通的 XPATH 或 XSLT(您实际上不必了解 XPATH 或 XSLT 即可使用它,别担心......它是一个 .NET 代码库,允许您解析“网络外”HTML 文件。解析器对“现实世界”格式错误的 HTML 非常宽容。对象模型与建议的 System.Xml 非常相似,但用于 HTML 文档(或流)。

7赞 Grimtron 9/19/2008 #8

前面已经提到过 Html Agility Pack - 如果你追求速度,你可能还想看看 Majestic-12 HTML 解析器。它的处理相当笨拙,但它提供了非常快速的解析体验。

9赞 Frank Schwieterman 3/9/2009 #9

我编写了一些提供“LINQ to HTML”功能的代码。我想我会在这里分享它。它基于 Majestic 12。它采用 Majestic-12 结果并生成 LINQ XML 元素。此时,您可以针对 HTML 使用所有 LINQ to XML 工具。举个例子:

        IEnumerable<XNode> auctionNodes = Majestic12ToXml.Majestic12ToXml.ConvertNodesToXml(byteArrayOfAuctionHtml);

        foreach (XElement anchorTag in auctionNodes.OfType<XElement>().DescendantsAndSelf("a")) {

            if (anchorTag.Attribute("href") == null)
                continue;

            Console.WriteLine(anchorTag.Attribute("href").Value);
        }

我想使用 Majestic-12,因为我知道它有很多关于 HTML 的内置知识,这些知识在野外发现。不过,我发现将 Majestic-12 结果映射到 LINQ 将接受为 XML 的内容需要额外的工作。我包含的代码做了很多清理工作,但是当你使用它时,你会发现被拒绝的页面。您需要修复代码以解决此问题。当抛出异常时,检查异常。Data[“source”],因为它可能被设置为导致异常的 HTML 标记。以良好的方式处理 HTML 有时并非易事......

因此,现在期望值实际上很低,这是代码:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Majestic12;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace Majestic12ToXml {
public class Majestic12ToXml {

    static public IEnumerable<XNode> ConvertNodesToXml(byte[] htmlAsBytes) {

        HTMLparser parser = OpenParser();
        parser.Init(htmlAsBytes);

        XElement currentNode = new XElement("document");

        HTMLchunk m12chunk = null;

        int xmlnsAttributeIndex = 0;
        string originalHtml = "";

        while ((m12chunk = parser.ParseNext()) != null) {

            try {

                Debug.Assert(!m12chunk.bHashMode);  // popular default for Majestic-12 setting

                XNode newNode = null;
                XElement newNodesParent = null;

                switch (m12chunk.oType) {
                    case HTMLchunkType.OpenTag:

                        // Tags are added as a child to the current tag, 
                        // except when the new tag implies the closure of 
                        // some number of ancestor tags.

                        newNode = ParseTagNode(m12chunk, originalHtml, ref xmlnsAttributeIndex);

                        if (newNode != null) {
                            currentNode = FindParentOfNewNode(m12chunk, originalHtml, currentNode);

                            newNodesParent = currentNode;

                            newNodesParent.Add(newNode);

                            currentNode = newNode as XElement;
                        }

                        break;

                    case HTMLchunkType.CloseTag:

                        if (m12chunk.bEndClosure) {

                            newNode = ParseTagNode(m12chunk, originalHtml, ref xmlnsAttributeIndex);

                            if (newNode != null) {
                                currentNode = FindParentOfNewNode(m12chunk, originalHtml, currentNode);

                                newNodesParent = currentNode;
                                newNodesParent.Add(newNode);
                            }
                        }
                        else {
                            XElement nodeToClose = currentNode;

                            string m12chunkCleanedTag = CleanupTagName(m12chunk.sTag, originalHtml);

                            while (nodeToClose != null && nodeToClose.Name.LocalName != m12chunkCleanedTag)
                                nodeToClose = nodeToClose.Parent;

                            if (nodeToClose != null)
                                currentNode = nodeToClose.Parent;

                            Debug.Assert(currentNode != null);
                        }

                        break;

                    case HTMLchunkType.Script:

                        newNode = new XElement("script", "REMOVED");
                        newNodesParent = currentNode;
                        newNodesParent.Add(newNode);
                        break;

                    case HTMLchunkType.Comment:

                        newNodesParent = currentNode;

                        if (m12chunk.sTag == "!--")
                            newNode = new XComment(m12chunk.oHTML);
                        else if (m12chunk.sTag == "![CDATA[")
                            newNode = new XCData(m12chunk.oHTML);
                        else
                            throw new Exception("Unrecognized comment sTag");

                        newNodesParent.Add(newNode);

                        break;

                    case HTMLchunkType.Text:

                        currentNode.Add(m12chunk.oHTML);
                        break;

                    default:
                        break;
                }
            }
            catch (Exception e) {
                var wrappedE = new Exception("Error using Majestic12.HTMLChunk, reason: " + e.Message, e);

                // the original html is copied for tracing/debugging purposes
                originalHtml = new string(htmlAsBytes.Skip(m12chunk.iChunkOffset)
                    .Take(m12chunk.iChunkLength)
                    .Select(B => (char)B).ToArray()); 

                wrappedE.Data.Add("source", originalHtml);

                throw wrappedE;
            }
        }

        while (currentNode.Parent != null)
            currentNode = currentNode.Parent;

        return currentNode.Nodes();
    }

    static XElement FindParentOfNewNode(Majestic12.HTMLchunk m12chunk, string originalHtml, XElement nextPotentialParent) {

        string m12chunkCleanedTag = CleanupTagName(m12chunk.sTag, originalHtml);

        XElement discoveredParent = null;

        // Get a list of all ancestors
        List<XElement> ancestors = new List<XElement>();
        XElement ancestor = nextPotentialParent;
        while (ancestor != null) {
            ancestors.Add(ancestor);
            ancestor = ancestor.Parent;
        }

        // Check if the new tag implies a previous tag was closed.
        if ("form" == m12chunkCleanedTag) {

            discoveredParent = ancestors
                .Where(XE => m12chunkCleanedTag == XE.Name)
                .Take(1)
                .Select(XE => XE.Parent)
                .FirstOrDefault();
        }
        else if ("td" == m12chunkCleanedTag) {

            discoveredParent = ancestors
                .TakeWhile(XE => "tr" != XE.Name)
                .Where(XE => m12chunkCleanedTag == XE.Name)
                .Take(1)
                .Select(XE => XE.Parent)
                .FirstOrDefault();
        }
        else if ("tr" == m12chunkCleanedTag) {

            discoveredParent = ancestors
                .TakeWhile(XE => !("table" == XE.Name
                                    || "thead" == XE.Name
                                    || "tbody" == XE.Name
                                    || "tfoot" == XE.Name))
                .Where(XE => m12chunkCleanedTag == XE.Name)
                .Take(1)
                .Select(XE => XE.Parent)
                .FirstOrDefault();
        }
        else if ("thead" == m12chunkCleanedTag
                  || "tbody" == m12chunkCleanedTag
                  || "tfoot" == m12chunkCleanedTag) {


            discoveredParent = ancestors
                .TakeWhile(XE => "table" != XE.Name)
                .Where(XE => m12chunkCleanedTag == XE.Name)
                .Take(1)
                .Select(XE => XE.Parent)
                .FirstOrDefault();
        }

        return discoveredParent ?? nextPotentialParent;
    }

    static string CleanupTagName(string originalName, string originalHtml) {

        string tagName = originalName;

        tagName = tagName.TrimStart(new char[] { '?' });  // for nodes <?xml >

        if (tagName.Contains(':'))
            tagName = tagName.Substring(tagName.LastIndexOf(':') + 1);

        return tagName;
    }

    static readonly Regex _startsAsNumeric = new Regex(@"^[0-9]", RegexOptions.Compiled);

    static bool TryCleanupAttributeName(string originalName, ref int xmlnsIndex, out string result) {

        result = null;
        string attributeName = originalName;

        if (string.IsNullOrEmpty(originalName))
            return false;

        if (_startsAsNumeric.IsMatch(originalName))
            return false;

        //
        // transform xmlns attributes so they don't actually create any XML namespaces
        //
        if (attributeName.ToLower().Equals("xmlns")) {

            attributeName = "xmlns_" + xmlnsIndex.ToString(); ;
            xmlnsIndex++;
        }
        else {
            if (attributeName.ToLower().StartsWith("xmlns:")) {
                attributeName = "xmlns_" + attributeName.Substring("xmlns:".Length);
            }   

            //
            // trim trailing \"
            //
            attributeName = attributeName.TrimEnd(new char[] { '\"' });

            attributeName = attributeName.Replace(":", "_");
        }

        result = attributeName;

        return true;
    }

    static Regex _weirdTag = new Regex(@"^<!\[.*\]>$");       // matches "<![if !supportEmptyParas]>"
    static Regex _aspnetPrecompiled = new Regex(@"^<%.*%>$"); // matches "<%@ ... %>"
    static Regex _shortHtmlComment = new Regex(@"^<!-.*->$"); // matches "<!-Extra_Images->"

    static XElement ParseTagNode(Majestic12.HTMLchunk m12chunk, string originalHtml, ref int xmlnsIndex) {

        if (string.IsNullOrEmpty(m12chunk.sTag)) {

            if (m12chunk.sParams.Length > 0 && m12chunk.sParams[0].ToLower().Equals("doctype"))
                return new XElement("doctype");

            if (_weirdTag.IsMatch(originalHtml))
                return new XElement("REMOVED_weirdBlockParenthesisTag");

            if (_aspnetPrecompiled.IsMatch(originalHtml))
                return new XElement("REMOVED_ASPNET_PrecompiledDirective");

            if (_shortHtmlComment.IsMatch(originalHtml))
                return new XElement("REMOVED_ShortHtmlComment");

            // Nodes like "<br <br>" will end up with a m12chunk.sTag==""...  We discard these nodes.
            return null;
        }

        string tagName = CleanupTagName(m12chunk.sTag, originalHtml);

        XElement result = new XElement(tagName);

        List<XAttribute> attributes = new List<XAttribute>();

        for (int i = 0; i < m12chunk.iParams; i++) {

            if (m12chunk.sParams[i] == "<!--") {

                // an HTML comment was embedded within a tag.  This comment and its contents
                // will be interpreted as attributes by Majestic-12... skip this attributes
                for (; i < m12chunk.iParams; i++) {

                    if (m12chunk.sTag == "--" || m12chunk.sTag == "-->")
                        break;
                }

                continue;
            }

            if (m12chunk.sParams[i] == "?" && string.IsNullOrEmpty(m12chunk.sValues[i]))
                continue;

            string attributeName = m12chunk.sParams[i];

            if (!TryCleanupAttributeName(attributeName, ref xmlnsIndex, out attributeName))
                continue;

            attributes.Add(new XAttribute(attributeName, m12chunk.sValues[i]));
        }

        // If attributes are duplicated with different values, we complain.
        // If attributes are duplicated with the same value, we remove all but 1.
        var duplicatedAttributes = attributes.GroupBy(A => A.Name).Where(G => G.Count() > 1);

        foreach (var duplicatedAttribute in duplicatedAttributes) {

            if (duplicatedAttribute.GroupBy(DA => DA.Value).Count() > 1)
                throw new Exception("Attribute value was given different values");

            attributes.RemoveAll(A => A.Name == duplicatedAttribute.Key);
            attributes.Add(duplicatedAttribute.First());
        }

        result.Add(attributes);

        return result;
    }

    static HTMLparser OpenParser() {
        HTMLparser oP = new HTMLparser();

        // The code+comments in this function are from the Majestic-12 sample documentation.

        // ...

        // This is optional, but if you want high performance then you may
        // want to set chunk hash mode to FALSE. This would result in tag params
        // being added to string arrays in HTMLchunk object called sParams and sValues, with number
        // of actual params being in iParams. See code below for details.
        //
        // When TRUE (and its default) tag params will be added to hashtable HTMLchunk (object).oParams
        oP.SetChunkHashMode(false);

        // if you set this to true then original parsed HTML for given chunk will be kept - 
        // this will reduce performance somewhat, but may be desireable in some cases where
        // reconstruction of HTML may be necessary
        oP.bKeepRawHTML = false;

        // if set to true (it is false by default), then entities will be decoded: this is essential
        // if you want to get strings that contain final representation of the data in HTML, however
        // you should be aware that if you want to use such strings into output HTML string then you will
        // need to do Entity encoding or same string may fail later
        oP.bDecodeEntities = true;

        // we have option to keep most entities as is - only replace stuff like &nbsp; 
        // this is called Mini Entities mode - it is handy when HTML will need
        // to be re-created after it was parsed, though in this case really
        // entities should not be parsed at all
        oP.bDecodeMiniEntities = true;

        if (!oP.bDecodeEntities && oP.bDecodeMiniEntities)
            oP.InitMiniEntities();

        // if set to true, then in case of Comments and SCRIPT tags the data set to oHTML will be
        // extracted BETWEEN those tags, rather than include complete RAW HTML that includes tags too
        // this only works if auto extraction is enabled
        oP.bAutoExtractBetweenTagsOnly = true;

        // if true then comments will be extracted automatically
        oP.bAutoKeepComments = true;

        // if true then scripts will be extracted automatically: 
        oP.bAutoKeepScripts = true;

        // if this option is true then whitespace before start of tag will be compressed to single
        // space character in string: " ", if false then full whitespace before tag will be returned (slower)
        // you may only want to set it to false if you want exact whitespace between tags, otherwise it is just
        // a waste of CPU cycles
        oP.bCompressWhiteSpaceBeforeTag = true;

        // if true (default) then tags with attributes marked as CLOSED (/ at the end) will be automatically
        // forced to be considered as open tags - this is no good for XML parsing, but I keep it for backwards
        // compatibility for my stuff as it makes it easier to avoid checking for same tag which is both closed
        // or open
        oP.bAutoMarkClosedTagsWithParamsAsOpen = false;

        return oP;
    }
}
}  

评论

1赞 Frank Schwieterman 3/9/2009
顺便说一句,HtmlAgilityPack 过去对我来说效果很好,我只是更喜欢 LINQ。
0赞 8/4/2011
添加 LINQ 转换时的性能如何?知道它与 HtmlAgilityPack 相比如何吗?
0赞 Frank Schwieterman 8/4/2011
我从来没有做过性能比较。这些天我使用 HtmlAgilityPack,麻烦少得多。不幸的是,上面的代码有很多特殊情况,我没有费心为它编写测试,所以我无法真正维护它。
0赞 Ruben Bartelink 11/12/2009 #10

如果您需要查看 JS 对页面的影响,请使用 WatiN [并且您准备启动浏览器]

16赞 Rob Volk 12/18/2009 #11

我找到了一个名为 Fizzler 的项目,它采用 jQuery/Sizzler 方法来选择 HTML 元素。它基于 HTML Agility Pack。它目前处于测试阶段,仅支持 CSS 选择器的一个子集,但使用 CSS 选择器而不是讨厌的 XPath 非常酷和令人耳目一新。

http://code.google.com/p/fizzler/

评论

1赞 Funka 5/14/2010
谢谢,这看起来很有趣!令我惊讶的是,jQuery的受欢迎程度如此之高,以至于很难找到一个受它启发的C#项目。现在,如果我能找到文档操作和更高级的遍历也是软件包的一部分就好了...... :)
0赞 Chi Chan 10/15/2010
我今天刚刚用过这个,我不得不说,如果你知道jQuery,它就很容易使用。
0赞 Mikos 1/3/2010 #12

根据您的需要,您可以选择功能更丰富的库。我尝试了大部分/所有建议的解决方案,但最突出的是 Html Agility Pack。它是一个非常宽容和灵活的解析器。

0赞 P M 3/23/2010 #13

试试这个脚本。

http://www.biterscripting.com/SS_URLs.html

当我将它与这个 url 一起使用时,

script SS_URLs.txt URL("http://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c")

它向我显示了此线程页面上的所有链接。

http://sstatic.net/so/all.css
http://sstatic.net/so/favicon.ico
http://sstatic.net/so/apple-touch-icon.png
.
.
.

您可以修改该脚本以检查图像、变量等。

0赞 Jonathan Wood 12/20/2010 #14

我写了一些用 C# 解析 HTML 标签的类。如果它们满足您的特定需求,它们既漂亮又简单。

您可以阅读有关它们的文章并在 http://www.blackbeltcoder.com/Articles/strings/parsing-html-tags-in-c 下载源代码。

http://www.blackbeltcoder.com/Articles/strings/a-text-parsing-helper-class 上还有一篇关于泛型解析帮助程序类的文章。

2赞 majmun 6/6/2011 #15

没有第三方库,可以在控制台上运行的WebBrowser类解决方案,并且 Asp.net

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;

class ParseHTML
{
    public ParseHTML() { }
    private string ReturnString;

    public string doParsing(string html)
    {
        Thread t = new Thread(TParseMain);
        t.ApartmentState = ApartmentState.STA;
        t.Start((object)html);
        t.Join();
        return ReturnString;
    }

    private void TParseMain(object html)
    {
        WebBrowser wbc = new WebBrowser();
        wbc.DocumentText = "feces of a dummy";        //;magic words        
        HtmlDocument doc = wbc.Document.OpenNew(true);
        doc.Write((string)html);
        this.ReturnString = doc.Body.InnerHtml + " do here something";
        return;
    }
}

用法:

string myhtml = "<HTML><BODY>This is a new HTML document.</BODY></HTML>";
Console.WriteLine("before:" + myhtml);
myhtml = (new ParseHTML()).doParsing(myhtml);
Console.WriteLine("after:" + myhtml);