在搜索引擎的開發(fā)中,我們需要對Html進行解析。本文介紹C#解析HTML的兩種方法。
AD:
在搜索引擎的開發(fā)中,我們需要對網(wǎng)頁的Html內(nèi)容進行檢索,難免的就需要對Html進行解析。拆分每一個節(jié)點并且獲取節(jié)點間的內(nèi)容。此文介紹兩種C#解析Html的方法。
C#解析Html的第一種方法:
用System.Net.WebClient下載Web Page存到本地文件或者String中,用正則表達式來分析。這個方法可以用在Web Crawler等需要分析很多Web Page的應(yīng)用中。
估計這也是大家最直接,最容易想到的一個方法。
轉(zhuǎn)自網(wǎng)上的一個實例:所有的href都抽取出來:
System.Collections.IEnumerator enu = matches.GetEnumerator();
while (enu.MoveNext() && enu.Current != null)
{
Match match = (Match)(enu.Current);
Console.Write(match.Value + "/r/n");
}
}
}
}
namespace HTMLParser
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
AddUrl();
}
private void btnParser_Click(object sender, EventArgs e)
{
#region 獲得網(wǎng)頁的html
try
{
txtHtmlWhole.Text = "";
string url = CBUrl.SelectedItem.ToString().Trim();
System.Net.WebClient aWebClient = new System.Net.WebClient();
aWebClient.Encoding = System.Text.Encoding.Default;
string html = aWebClient.DownloadString(url);
txtHtmlWhole.Text = html;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
#region 分析網(wǎng)頁html節(jié)點
Lexer lexer = new Lexer(this.txtHtmlWhole.Text);
Parser parser = new Parser(lexer);
NodeList htmlNodes = parser.Parse(null);
this.treeView1.Nodes.Clear();
this.treeView1.Nodes.Add("root");
TreeNode treeRoot = this.treeView1.Nodes[0];
for (int i = 0; i < htmlNodes.Count; i++)
{
this.RecursionHtmlNode(treeRoot, htmlNodes[i], false);
}
#endregion
}
private void RecursionHtmlNode(TreeNode treeNode, INode htmlNode, bool siblingRequired)
{
if (htmlNode == null || treeNode == null) return;
TreeNode current = treeNode;
TreeNode content ;
//current node
if (htmlNode is ITag)
{
ITag tag = (htmlNode as ITag);
if (!tag.IsEndTag())
{
string nodeString = tag.TagName;
if (tag.Attributes != null && tag.Attributes.Count > 0)
{
if (tag.Attributes["ID"] != null)
{
nodeString = nodeString + " { id=/"" + tag.Attributes["ID"].ToString() + "/" }";
}
if (tag.Attributes["HREF"] != null)
{
nodeString = nodeString + " { href=/"" + tag.Attributes["HREF"].ToString() + "/" }";
}
}
current = new TreeNode(nodeString);
treeNode.Nodes.Add(current);
}
}
//獲取節(jié)點間的內(nèi)容
if (htmlNode.Children != null && htmlNode.Children.Count > 0)
{
this.RecursionHtmlNode(current, htmlNode.FirstChild, true);
content = new TreeNode(htmlNode.FirstChild.GetText());
treeNode.Nodes.Add(content);
}
//the sibling nodes
if (siblingRequired)
{
INode sibling = htmlNode.NextSibling;
while (sibling != null)
{
this.RecursionHtmlNode(treeNode, sibling, false);
sibling = sibling.NextSibling;
}
}
}
private void AddUrl()
{
CBUrl.Items.Add("http://www.hao123.com");
CBUrl.Items.Add("http://www.sina.com");
CBUrl.Items.Add("http://www.heuet.edu.cn");
}
}
}
實現(xiàn)取來很容易,結(jié)合Winista.Htmlparser源碼很快就可以實現(xiàn)想要的效果。
小結(jié):
簡單介紹了兩種C#解析Html的的方法,大家有什么其他好的方法還望指教。
新聞熱點
疑難解答
圖片精選