2012-04-28 31 views
1

我其实想虎视眈眈从具有某些子标签如何让只从HTML父标签文本在C#

例如标签文字:

<p><span>Child Text </span><span class="price">Child Text</span><br /> 
I need this text</p> 

这是什么我试图

HtmlElement menuElement = browser.Document.GetElementsByTagName("p"); 
String mytext = menuElement.InnerHtml; //also tried innerText,OuterHtml,OuterText 

更新:我觉得我必须使用Htmlagilitypack,所以现在我的问题是如何做到THI使用htmlagilitypack lib,我是新手。

感谢

+0

因为您需要在c#中找到,请从问题 – 2012-04-28 19:34:41

+0

中删除javascript标签@CharandeepSingh - 您可以对标签进行建议编辑,您知道吗? – Oded 2012-04-28 19:35:07

+0

基本上你需要直接的子节点,它是一个文本节点。不确定这可以通过'HtmlElement'实现。 HTML敏捷包在这方面可能更加灵活。 – Oded 2012-04-28 19:36:33

回答

2

使用正则表达式到web scrapping库有很多方法可以解决这个问题。我建议你使用htmlagilitypack,你可以通过xpath来准确解决你需要的东西。 为HtmlAgilityPack添加引用和命名空间,我使用linq(这需要.net 3.5或更高版本),下面的代码可以做到这一点。

using HtmlAgilityPack; 
using System.Linq; 

//这些参考文件必须可用。

 private void Form1_Load(object sender, EventArgs e) 
     { 
      var rawData = "<p><span>Child Text </span><span class=\"price\">Child Text</span><br />I need this text</p>"; 
      var html = new HtmlAgilityPack.HtmlDocument(); 
      html.LoadHtml(rawData); 
      html.DocumentNode.SelectNodes("//p/text()").ToList().ForEach(x=>MessageBox.Show(x.InnerHtml)); 
     } 
0

它的多,如果你可以把“需要这个文本”的跨度内带有ID很容易 - 那么你只要抓住该ID的.innerHTML()。如果您无法更改标记,则可以在“
”之后获取menuElement的.innerHTML()和字符串匹配内容,但这非常脆弱。

+0

感谢robrich,但我不能更改html代码,进一步我有很多标签,我想通过循环抓住,所以匹配字符串不是选择4我。 – 2012-04-28 19:37:58

0

您可以通过将DocumentText拆分为不同的部分来获取文本。

string text = "<p><span>Child Text </span><span class="price">Child Text</span><br />I need this text</p>"; 
text = text.Split(new string{"<p><span>Child Text </span><span class="price">Child Text</span><br />"}, StringSplitOptions.None)[1]; 
// Splits the first part of the text, leaving us with "I need this text</p>" 
// We can remove the last </p> many ways, but here I will show you one way. 
text = text.Split(new string{"</p>"}, StringSplitOptions.None)[0]; 
// text now has the value of "I need this text" 

希望对您有所帮助!