Nodejs写的搬家工具知识分享
這篇文章 主要學(xué)習(xí)這兩個(gè)模塊的使用:
request-promise-native :?https://github.com/request/request-promise-native cheerio :https://github.com/cheeriojs/cheerionodejs有個(gè)request模塊,專(zhuān)門(mén)處理這些網(wǎng)絡(luò)請(qǐng)求方面的。 就像.NET也有request,webclient,httpclient啥的。。。
nodejs的request使用方法在這,自己查一下:?https://github.com/request/request
而我喜歡用async和await的寫(xiě)法,因此我還引入了request-promise-native 模塊,?https://github.com/request/request-promise-native? ,這個(gè)就相當(dāng)于.NET中httpclient吧。
好了背景就講這么多,我們就開(kāi)始簡(jiǎn)單的使用request-promise-native,進(jìn)行模擬提交。
我用淘寶鏡像安裝模塊,會(huì)比較快比較快一些,注冊(cè)淘寶鏡像方式:
npm install -g cnpm --registry=https://registry.npm.taobao.org然安裝模塊:
cnpm install --save request cnpm install --save request-promise-native?
我們登陸后 ,嘗試發(fā)一篇文章,然我們分析一下提交的東西:
主要是 Cookie以及 FormData。
好了,然后我們寫(xiě)一個(gè) cnblogs,來(lái)處理提交,代碼:
const request = require('request-promise-native'); // const proxy = 'http://127.0.0.1:8888'; const url = 'https://i.cnblogs.com/EditPosts.aspx?opt=1'; class Cnblogs {static async save({ title, content, postdate }) {let response = await request({url: url,method: 'POST',headers: {Cookie: '[隱私隱私隱私]',},form: {__VIEWSTATE: '===========',__VIEWSTATEGENERATOR: 'FE27D343',Editor$Edit$txbTitle: title,Editor$Edit$EditorBody: `<p style="color: red; font-weight: bold;">原文發(fā)布時(shí)間為:${postdate} —— 來(lái)源于本人的百度文章 [由搬家工具導(dǎo)入]</p>${content}`,Editor$Edit$APOptions$Advancedpanel1$cklCategories$0: '1031596',Editor$Edit$Advanced$ckbPublished: 'on',Editor$Edit$Advanced$chkDisplayHomePage: 'on',Editor$Edit$Advanced$chkComments: 'on',Editor$Edit$Advanced$chkMainSyndication: 'on',Editor$Edit$lkbPost: '發(fā)布'}});return response;} }module.exports = Cnblogs; 嗯,我們建立一個(gè) app.js 調(diào)用一下測(cè)試吧: const cnblogs = require('./cnblogs');const main = async () => {try {let response = await cnblogs.save('測(cè)試','測(cè)試內(nèi)容','2018-01-01');console.log(response);} catch (err) {console.error('[ERROR]', err);} };main(); 執(zhí)行node app,我們發(fā)現(xiàn), 導(dǎo)入成功了。。。。 我用類(lèi)似的方法 從自己百度文章抓取文章,然后調(diào)用?cnblogs.save(); 進(jìn)行導(dǎo)入:?
抓取文章也是很簡(jiǎn)單的,為了方便從response查找dom,我們可以用這個(gè)模塊?cheerio :?https://github.com/cheeriojs/cheerio , 就類(lèi)似于我們做.NET的時(shí)候會(huì)用?HtmlAgilityPack 來(lái)查找dom一樣。
cheerio 可以去看看,他的語(yǔ)法跟jquery一樣,使用起來(lái)很方便。
總結(jié)
以上是生活随笔為你收集整理的Nodejs写的搬家工具知识分享的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 前端学习(1656):前端系列实战课程之
- 下一篇: RS232 DB9 计算机接口定义