httpagility包在破坏的标签之间刮擦

时间:2012-06-02 06:59:27

标签: vb.net visual-studio-2010 http html-parsing html-agility-pack

我需要刮一个带有h3标签但后面没有关闭p标签的p标签。它看起来像这样:

<script ad>asdasdasd</script>
<p>Translation companies are
-----------------------
-----------------------
<h3 class="this_class">mind blown site</h3>

没有&lt; / p&gt;标签所以我无法完全解析它。现在我有两个问题:

1)可以使用httpagility xpath解析吗?

2)我有一个函数来查找两个字符串之间的文本(getbetween)。但我有一个疑问 - 如果我使用“asdasdasd”和“它总是100%,vb.net将使用高于h3的脚本标签,因为有2-3条相同的线 - ”asdasdasd“

3)你们都知道的其他方法吗?

(必须在代码中写,所以html不会搞砸)

此致

2 个答案:

答案 0 :(得分:1)

最好发布一些更“真实”的HTML来真正帮助你,至少是h3p之间的标签。 无论如何,这应该会从p代码中获取h3- - 代码。

HtmlDocument doc = new HtmlDocument();
doc.Load(... //Load the Html...

//Either of these lines will do
HtmlNode pNode = doc.DocumentNode.SelectSingleNode("//h3[@class='this_class']/preceding-sibling::p");
//HtmlNode pNode = doc.DocumentNode.SelectSingleNode("//h3[contains(text(),'mind blown site')]/preceding-sibling::p");

string pInnerHtml = pNode.NextSibling.InnerHtml; //Has the text "Translation companies are...."

答案 1 :(得分:0)

一般来说,要将所有节点从开放的p标记添加到您不想要的标记的开头,您可以这样做:

var p = doc.DocumentNode.SelectSingleNode("//p");
var h3 = p.SelectSingleNode("following-sibling::h3[@class='this_class']");
var following = new List<string>();
for (var current = p.NextSibling; current != h3; current = current.NextSibling)
{
    following.Add(current.InnerText);
}
var innerText = String.Concat(following);