Two ways to parse HTML under C # Introduction

Source: Internet
Author: User
Tags lexer
In the search engine development, we need to parse the HTML. This article describes two methods of parsing HTML in C #.
AD:
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 of parsing HTML in C #:
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"); 
} 
} 
} 
}


The second method of parsing HTML in C #:
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 the html of the 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 Analyzing 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 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 to the two methods of C # parsing HTML, we have what other good way to look at the advice.


Related Article

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.