C # parsing HTML

Source: Internet
Author: User
Tags lexer

In the search engine development, we need to search the HTML content of the webpage, inevitably need to parse the HTML. Splits each node and gets the content between nodes. This article describes two methods of parsing HTML in C #.
The first method:
Use System.Net.WebClient to download the Web page to a local file or string and parse it with a regular expression. This method can be used in applications such as web crawler that need to analyze a lot of Web page.
This is also the most direct, the most easy to think of a method.
Turn from an example on the Web: all the href are extracted:



Using System;
Using System.Net;
Using System.Text;
Using System.Text.RegularExpressions;
Namespace HttpGet
{
Class Class1
{
[STAThread]
static void Main (string[] args)
{
System.Net.WebClient client = new WebClient ();
byte[] page = client. Downloaddata ("http://www.google.com");
String content = System.Text.Encoding.UTF8.GetString (page);
String regex = "href=[\\\" \\\ "(http:\\/\\/|\\.\\/|\\/)? \\w+ (\\.\\w+) * (\\/\\w+ (\\.\\w+)?) * (\\/|\\?\\w*=\\w* (&\\w*=\\w*) *)? [\\\"\\\‘]";
Regex re = new regex (regex);
MatchCollection matches = Re. Matches (content);

System.Collections.IEnumerator enu = matches. GetEnumerator ();
while (ENU. MoveNext () && enu. current = null)
{
Match match = (match) (ENU. Current);
Console.Write (match. Value + "\ r \ n");
}
}
}
}

A similar approach is used in the HTML parsing of some reptiles.
The second method:

Parsing HTML with Winista.Htmlparser.Net. This is. NET platform to parse the open source code of HTML, online source download, Baidu will be able to search a bit, here is not provided. And there are help documents in English. Can not find the left mailbox.
Personally think that this is the. NET platform to resolve the HTML good solution, basically to meet our parsing of HTML.
Made an example of yourself:


Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using Winista.Text.HtmlParser;
Using Winista.Text.HtmlParser.Lex;
Using Winista.Text.HtmlParser.Util;
Using Winista.Text.HtmlParser.Tags;
Using Winista.Text.HtmlParser.Filters;


Namespace Htmlparser
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
Addurl ();
}

private void Btnparser_click (object sender, EventArgs e)
{
#region Get HTML for a Web page
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 parsing Web page HTML nodes
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);
}
}

Get the content between nodes
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");
}



}
}

Operating effect:
Implementation is easy, combined with Winista.htmlparser source code will soon be able to achieve the desired effect.

Summary:
A brief introduction of two methods of parsing HTML, we have what other good way to look at the advice.

C # parsing HTML

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.