使用HTMLAgilityPack解析HTML

时间:2011-11-28 19:44:16

标签: c# html-agility-pack

我正在尝试使用HTML Agility Pack解析以下HTML。

这是代码返回的整个文件的片段:

<div class="story-body fnt-13 p20-b user-gen">
    <p>text here text here text </p>
    <p>text here text here text text here text here text text here text here text text here text here text </p>
    <div  class="gallery clr bdr aln-c js-no-shadow mod  cld">
        <div>
            <ol>
                <li class="fader-item aln-c ">
                    <div class="imageWrap m10-b">
                       &#8203;<img class="http://www.domain.com/picture.png| " src="http://www.domain.com/picture.png" alt="alt text" />
                    </div>
                    <p class="caption">caption text</p>
                </li>
            </ol>
        </div>
    </div >
    <p>text here text here text text here text here text text here text here text text here text here text </p>
    <p>text here text here text text here text here text text here text here text text here text here text text here text here text </p>
    <p>text here text here text text here text here text text here text here text text here text here text text here text here text </p>
</div>

我使用以下内容得到这段代码(我知道这很麻烦)

string url = "http://www.domain.com/story.html";
var webGet = new HtmlWeb();
var document = webGet.Load(url);

var links = document.DocumentNode
        .Descendants("div")
        .Where(div => div.GetAttributeValue("class", "").Contains("story-body fnt-13 p20-b user-gen")) //
        .SelectMany(div => div.Descendants("p"))
        .ToList();
int cn = links.Count;

HtmlAgilityPack.HtmlNodeCollection tl = document.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]");
foreach (HtmlAgilityPack.HtmlNode node in tl)
{
    textBox1.AppendText(node.InnerText.Trim());
    textBox1.AppendText(System.Environment.NewLine);
}

代码遍历每个p并且(现在)将其附加到文本框。除了div标记以及类gallery clr bdr aln-c js-no-shadow mod cld之外,所有标记都正常工作。这一点HTML的结果是我得到&#8203;和标题文本位。

从结果中省略这一点的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

XPATH是你的朋友。试试这个,忘掉那个糟糕的xlink语法: - )

HtmlNodeCollection tl = document.DocumentNode.SelectNodes("//p[not(@*)]");
foreach (HtmlAgilityPack.HtmlNode node in tl)
{
    Console.WriteLine(node.InnerText.Trim());
}

此表达式将选择所有未设置任何属性的P节点。请参阅此处了解其他样本:XPath Syntax

答案 1 :(得分:1)

目前还不清楚你在问什么。我你问的是如何获得特定div的直接后代。如果是这种情况,请使用ChildNodes而不是Descendants。那就是:

.SelectMany(div => div.ChildNodes().Where(n => n.Name == "p"))

问题是Descendants完全递归文档树。