我正在使用正则表达式来解析HTML,但有些文章说HTMLAgilityPack要容易得多.对我来说最大的问题是如何解析这个示例的html(twitter):
这个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>
Run Code Online (Sandbox Code Playgroud)
我希望它像这样输出:
"多么棒的一天!冒险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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
我只是自己测试了这个打印出来
What an awesome day! Adventure nanaman kahapon #ondoy #eurotel #retail #family"
Run Code Online (Sandbox Code Playgroud)
请注意,如果您要在实际的Twitter页面上运行这段代码,则会有多条推文,因此您需要对上面发布的代码进行一些修改.但这应该会让你对如何使用它有一个好主意.