Node. js uses cheerio to create a simple web crawler example, node. jscheerio

Source: Internet
Author: User

Node. js uses cheerio to create a simple web crawler example, node. jscheerio

This article describes how to use cheerio to create a simple web crawler example for Node. js:

1. Objectives

  1. Obtain the website title information
  2. Output the obtained information to a new file.
  3. Tool: cheerio. Use npm to download npm install cheerio
  4. The use of cheerio APIS is basically the same as that of jQuery APIs.
  5. If you are familiar with jQuery, cheerio will get started soon.

2. Code Section

Introduction: Get the sequence of the segment faultpage, and output the obtained sequence number to the pagetitle.txt file at the end.

Const https = require ('https'); const fs = require ('fs'); const cheerio = require ('cheerio '); const url = 'https: // segmentfault.com/'{https.get (url, (res) =>{ let html = ''; res. on ('data', (data) =>{ html + = data ;}); res. on ('end', () =>{ getPageTitle (html );});}). on ('error', () => {console. log ('webpage information error get');}); function getPageTitle (html) {const $ = cheerio. load (html); let chapters = $ ('. news _ item-title '); let data = []; let index = 0; let fileName = 'pageTitle.txt'; for (let I = 0; I <chapters. length; I ++) {let chapterTitle = $ (chapters [I]). find ('A '). text (). trim (); index ++; data. push ('\ n $ {index}, $ {chapterTitle}');} fs. writeFile (fileName, data, 'utf8', (err) =>{ if (err) {console. log ('fs file system failed to create new file ', err);} console. log ('successfully put the obtained title in the new file $ {fileName ')})}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.