首页 » 网站推广 » nodejs爬虫php页面技巧_快速用NodeJs编写一个爬虫抓取网站数据

nodejs爬虫php页面技巧_快速用NodeJs编写一个爬虫抓取网站数据

访客 2024-11-02 0

扫一扫用手机浏览

文章目录 [+]

下面是它的大略用法:

默认是get方法,还有post方法,但我们本日要做的爬虫用不到post就不讲了。

nodejs爬虫php页面技巧_快速用NodeJs编写一个爬虫抓取网站数据

var request = require('request');request('url你的要求', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // 要求成功的处理逻辑 }});

nodejs爬虫php页面技巧_快速用NodeJs编写一个爬虫抓取网站数据
(图片来自网络侵删)
其次要熟习cheerio模块

cheerio是为做事器特殊定制的,快速、灵巧、履行的jQuery核心实现。
大略,易用,灵巧,反正你会用jQuery就可以利用它,当然也会有一些细微的差别。

举个例子:

// 引入cheerio模块const cheerio = require('cheerio')// 加载HTML字符串const $ = cheerio.load('<h4 class=\公众title\"大众>Hello world</h4>') // 设置Text$('h4.title').text('Hello there!')// 添加class$('h4').addClass('welcome') // 获取完全HTML$.html()//=> <html><head></head><body>// <h4 class=\"大众title welcome\"大众>Hello there!</h4></body></html>

利用iconv-lite来搞定乱码问题

nodejs只支持utf-8,node没有供应转换编码的原生支持,iconv-lite,可以实现编码转换,

举个例子:

var http = require(\"大众http\"大众);var iconv = require(\"大众iconv-lite\公众);var url = \"大众http://hq.sinajs.cn/list=sh600595\公众;var req = http.request(url, function(res){ res.on('data',function(data){ data = iconv.decode(data, 'GBK'); console.log(data); });});req.end();

理解了上面的代码就差不多了,接下来开始完成网络爬虫代码编写:

const request = require('request');const cheerio = require('cheerio');var iconv = require('iconv-lite');var options = { url: \公众https://jiage.autohome.com.cn/price/carlist/p-35368\"大众, method: 'GET', encoding: null}request(options, function(error, response, body) { classList = []; if (!error && response.statusCode === 200) { var buf = iconv.decode(body, 'utf8').toString(); //解码gb2312 var $ = cheerio.load(buf); // 导航 _src = $(\"大众.caricon-list dd a\"大众).each(async function(index) { var $me = $(this); if (index > 0 && index < 9) { var item = { id: index, url: $me.attr('href'), name: $me.children('span').text() || \公众未知\"大众 }; let url = $me.attr('href'); let name = $me.children('span').text() || \"大众未知\"大众; try { const car = await MyClassList.insert({ url: url, name: name }) } catch (e) { console.log(e) } classList.push(item); } })

上面的代码是request读取到页面上的数据,然后利用iconv办理乱码问题,在利用cheerio把我们须要的数据取出来重新整理,以备后续利用。

鉴于篇幅限定,后续代码先容请持续关注。

标签:

相关文章

今日头条算法引领个化信息时代的变革

信息爆炸时代已经到来。每个人都是信息的接收者和传播者。面对海量的信息,人们往往感到无所适从。为了解决这一问题,各大互联网公司纷纷推...

网站推广 2025-01-31 阅读1 评论0

今日头条算法信息推荐的秘密武器

信息爆炸的时代已经来临。人们每天都会接触到大量的信息,而如何从这些信息中筛选出有价值的内容,成为了亟待解决的问题。今日头条算法作为...

网站推广 2025-01-31 阅读1 评论0

今日头条算法精准推荐背后的技术奥秘

信息爆炸的时代已经来临。我们每天都要面对海量的信息,如何从这些信息中筛选出自己感兴趣的内容,成为了每个人都关心的问题。今日头条作为...

网站推广 2025-01-31 阅读1 评论0