提取段落标签中的内容

时间:2010-12-20 17:35:21

标签: c# html webclient

我在字符串中跟随html并且我必须仅在Paragraph标签中提取内容的任何想法吗?

链接是http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml

我试过了

  const string HTML_TAG_PATTERN = "<[^>]+.*?>";
    static string StripHTML(string inputString)
            {
                return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty);
            }

它删除了所有的html标签,但我不想删除所有的标签,因为这是我如何获得像标签段落的内容

其次它在文本中对\ n进行换行,并且应用replace(“\ n”,“”)剂量没有帮助 一个问题是,当我申请时

int UrlStart = e.Result.IndexOf("<p>"), urlEnd = e.Result.IndexOf("<p>&nbsp;</p></td>\r" );
     string paragraph = e.Result.Substring(UrlStart, urlEnd);
     extractedContent.Text = paragraph.Replace(Environment.NewLine, "");

<p>&nbsp;</p></td>\r这会出现在段落的末尾,但urlEnd不能确保只显示段落

提取的字符串在visual studio中显示如下 alt text 此页面由Webclient下载 HTML页面结束

We will provide ourselves with ropes of\rsuitable length and strength- and- pardon me- you must not\rdrink more to-night.  our hands and feet must be steady and\rfirm tomorrow.\"\r<p>&nbsp;</p>     </td>\r    </tr>\r\r    <tr>\r     <td height=\"25\" width=\"10%\">\r     \r     </td><td height=\"25\" width=\"80%\" align=\"center\">\r       <font color=\"#FFFFFF\">\r       <font size=\"4\">1</font> &nbsp;\r       </font></td>\r     <td height=\"25\" width=\"10%\" align=\"right\"><a href=\"C2P1.shtml\">Next</a></td>\r    </tr>\r   </table>\r  </center>\r</div>\r<p align=\"center\"><a href=\"index.shtml\"><b>The Coming Race -by- Edward Bulwer Lytton</b></a></p>\r<P><B><center><A HREF=\"http://www.public-domain-content.com/encyclopedia.shtml\">Encyclopedia</a> - <A HREF=\"http://www.public-domain-content.com/books.shtml\">Books</a> - <A HREF=\"http://www.public-domain-content.com/religion.shtml\">Religion<a/> - <A HREF=\"http://www.public-domain-content.com/links2.shtml\">Links</a> - <A HREF=\"http://www.public-domain-content.com/\">Home</a> - <A HREF=\"http://www.webmaster-headquarters.com/mb/\">Message Boards</a></B><BR>This <a HREF=\"http://www.wikipedia.org/\">Wikipedia</a> content is licensed under the <a href=\"http://www.gnu.org/copyleft/fdl.html\">GNU Fr

1 个答案:

答案 0 :(得分:2)

不要使用正则表达式来解析HTML。请改用HTML Agility Pack(或类似的东西)。

一个简单的例子,但你可以这样做:

HtmlDocument document = new HtmlDocument();
document.Load("your_file_here.htm");
foreach(HtmlNode paragraph in document.DocumentElement.SelectNodes("//p"))
{
    // do something with the paragraph node here
    string content = paragraph.InnerText; // or something similar
}