我正在使用正则表达式来解析HTML,但是有些文章说HTMLAgilityPack要容易得多。对我来说最大的问题是如何为这个样本(twitter)解析html:
这是HTML代码:
<p class="js-tweet-text tweet-text"> What an awesome day! Adventure nanaman kahapon <a href="http" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr"><s>#</s><b><strong>ondoy</strong></b></a> <a href="https://twitter.com/search?q=%23eurotel&src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr"><s>#</s><b>eurotel</b></a> <a href="https://twitter.com/search?q=%23retail&src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr"><s>#</s><b>retail</b></a> <a href="https://twitter.com/search?q=%23family&src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr"><s>#</s><b>family</b></a></p>
我希望它输出如下:
“多么棒的一天!冒险nanaman kahapon #ondoy #eurotel #retail #family”
如何解析该HTML代码。我现在正在使用正则表达式,但它显示其他标签,如href。
这是我的正则代码。
WebClient web = new WebClient();
string html = web.DownloadString(filename);
MatchCollection m1 = Regex.Matches(html, "<p class=\"js-tweet-text tweet-text\">\\s*(.+?)\\s*</p>", RegexOptions.Singleline);
foreach (Match m in m1)
{
MessageBox.Show(m.Groups[1].Value);
}
答案 0 :(得分:5)
HtmlWeb p = new HtmlWeb();
var doc= p.Load(@"link your HTML page");
var node = doc.DocumentNode.SelectNodes("//p[@class='js-tweet-text tweet-text']").FirstOrDefault();
if (node != null)
{
Console.WriteLine(node.InnerText);
}
我自己测试了它,然后打印出来
What an awesome day! Adventure nanaman kahapon #ondoy #eurotel #retail #family"
请注意,如果您要在实际的Twitter页面上运行此代码,则会有多条推文,因此您需要对上面发布的代码进行一些修改。但这应该会让你对如何使用它有个好主意。