//过滤html标签
static void InnerText()
{
HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument doc = htmlWeb.Load("http://www.cnblogs.com/", "GET");
HtmlNode rootNode = doc.DocumentNode;
Console.WriteLine(rootNode.InnerHtml);
//Console.WriteLine(rootNode.InnerText);
} //选择器
static void GetBlogs()
{
string url = "http://www.cnblogs.com/";
HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument doc = htmlWeb.Load(url, "GET");
//doc.GetElementbyId("aa");
HtmlNode rootNode = doc.DocumentNode;
HtmlNodeCollection h3Nodes = rootNode.SelectNodes("//div[@class='post_item_body']/h3");
foreach (var h3Node in h3Nodes)
{
HtmlNode aNode = h3Node.SelectSingleNode("a"); //筛选a标签节点
HtmlNode pNode = h3Node.NextSibling.NextSibling; //下一个节点
string blogLink = aNode.GetAttributeValue("href", ""); //获取元素属性
string title = aNode.InnerText;
string content = pNode.InnerText;
Console.WriteLine(title);
Console.WriteLine(blogLink);
Console.WriteLine(content);
Console.WriteLine("------------------------------------------------------");
}
return;
} //XPath表达式
static void XPathTest()
{
string path = @"test.html";
HtmlDocument doc = new HtmlDocument();
HtmlNode rootNode = doc.DocumentNode;
doc.Load(path);
//获取h1标签
var h1 = rootNode.SelectSingleNode("/html/body/div[1]/h1[1]");
Console.WriteLine(h1.InnerText);
//获取ul>li 姓名标签
var liName = rootNode.SelectSingleNode("/html/body/div[2]/ul[1]/li[1]");
Console.WriteLine(liName.InnerText);
//获取ul>li 年龄标签
var liAge = rootNode.SelectSingleNode("/html/body/div[2]/ul[1]/li[2]");
Console.WriteLine(liAge.InnerText);
}
test.html代码如下:
<html>
<head>
</head>
<body>
<div>
<h1>欢迎访问这个网页!</h1>
</div> <div>
<ul class="user_match clear">
<li>姓名:张三</li>
<li>年龄:18</li>
</ul>
</div>
</body>
</html>