Recently I got node. js and wrote a demo for parsing html to get information.
First try, then this blog is about to open the knife .... First:
Test. js ==>
[Javascript]
Var $ = require ('jquery ');
Var http = require ('http ');
Var options = {
Host: 'blog .csdn.net ',
Port: 80,
Path: '/lqg1122'
}; Www.2cto.com
Var html = '';
Http. get (options, function (res ){
Res. on ('data', function (data ){
// Collect the data chunks to the variable named "html"
Html + = data;
}). On ('end', function (){
// The whole of webpage data has been collected. parsing time!
Var title = $ (html). find ('div h3 span '). each (function ($ this ){
Var a = $ (this). children ('A'). attr ('href ');
Var B = $ (this). children ('A'). text ();
Console. log (B + ":" + options. host + );
});
Console. log ("over ");
});
});
Here, the jquery library is added to support html Parsing. You must install it first:
$ Npm install jquery
The code is parsed here: the function to be implemented here is to obtain the name and link address of the blog directory on the current page. First, you must obtain the html of the entire page,
Options parameters are the resource domain name, port, and path of the page;
The global html variables defined above mean the entire page by default;
The get method of the http module of nodejs is used to read data and the listern of data is enabled. when data is read, 'data' is triggered ';
When the data is read, 'end' is triggered '. Therefore, the parsing will be completed after the data is read.
Right-click the page source code to view the href and text content of several sections similar to the following html code:
[Html]
<Div id = "article_list" class = "list">
<Div class = "list_item article_item">
<Div class = "article_title">
<Span class = "ico ico_type_Original"> </span>
<H3>
<Span class = "link_title"> <a href = "/lqg1122/article/details/8172645">
Use Jekyll-Bootstrap to set up a simple github blog record
</A> </span>
</H3>
</Div>
Find h3 under the div node by using the. find () method and then find the following node span,
Because multiple objects are matched, each is added here to perform the same operation on each object (take out the href value, extract the text content, and then output it on the terminal ).
Note that when the href value is used, html has been decomposed into the span node. We can see from the preceding html source code snippet that there are two nodes under the span node, we want the node a, so we have children ('A') and then get the value. Run node test. js and you can see that the terminal has the expected output.
I think node. js is quite fun. You can play it slowly ~