
問題:網(wǎng)站如果被大量用戶使用時,服務器要完成大量發(fā)送數(shù)據(jù)和插入數(shù)據(jù)任務。
解決:為了保持服務的友好性,并保持合理的響應時間,在返回數(shù)據(jù)時,用分頁功能來返回部分。經(jīng)常使用的數(shù)據(jù),可以使用內存來緩存,使其能快速發(fā)送(本文就不討論了)。
本文內容如下:
- 抓取數(shù)據(jù)
- 保存數(shù)據(jù)
- 實現(xiàn)分頁功能
- 不足之處
- 參考網(wǎng)站
1.抓取數(shù)據(jù)
- 安裝Python2.7和Scrapy。目前Scrapy對2.*版本支持比較好。
- 創(chuàng)建一個posts項目。運行:
scrapy startproject posts - 設置posts/items.py。設置需要顯示系統(tǒng)信息,網(wǎng)站信息和抓取信息的字段列表,如下所示(代碼不全):
# Primary fields
title = Field()
view = Field()
updated = Field()
image_urls = Field()
link = Field()
# Calculated fields
images = Field()
location = Field()
# Housekeeping fields
url = Field()
project = Field()
spider = Field()
server = Field()
date = Field()
- 使用CrawlSpider類進行雙向抓取。運行:
scrapy genspider -t crawl easy web
然后修改spiders/easy.py,如下所示(設置雙向抓?。?/li>
rules = (
Rule(LinkExtractor(restrict_xpaths='//a[contains(@class, "buttonright")]')),
Rule(LinkExtractor(restrict_xpaths='//a[contains(@class, "result_link")]'), callback='parse_item')
)
- 抓取數(shù)據(jù)。在終端中,運行:
scrapy crawl easy -s CLOSESPIDER_ITEMCOUNT=50 -o item.json
//向網(wǎng)站抓取50條數(shù)據(jù),并保存到item.json文件中
2.保存數(shù)據(jù)
- 讀取item.json數(shù)據(jù)。在根目錄創(chuàng)建contacts.js,并添加如下內容:
import fs from "fs";
const Data = JSON.parse(fs.readFileSync("./posts/items.json"));
//篩選數(shù)據(jù)
const posts = Data.map((post) => {
if(post.hasOwnProperty("updated")){
return Object.assign({}, {
title: post.title[0],
link: post.url[0],
view: post.view[0],
updated: post.updated[0]
})
}else{
return {}
}
});
//去掉{},抓取的數(shù)據(jù)保存到postsData中
const postsData = posts.filter((value) => {
return Object.keys(value).length
})
- 創(chuàng)建一個posts數(shù)據(jù)庫。在根目錄中創(chuàng)建index.js,并添加如下所示:
const postsSchema = new mongoose.Schema({
title: { type: String },
link: { type: String },
view: { type: String },
updated: { type: String }
});
const Posts = mongoose.model("Post", postsSchema);
- 將數(shù)據(jù)保存到數(shù)據(jù)庫中
postsData.map(value => {
let item = new Posts(value);
item.save((error, result) => {
if (error) {
throw error;
}
});
});
3.實現(xiàn)分頁功能
- 安裝依賴包。運行:
cnpm install express-paginate mongoose-paginate --save - 設置返回頁數(shù)值。下面代碼中:10表示默認返回10條數(shù)據(jù),50表示最大返回條數(shù)不會超過50條。
app.use(expressPaginate.middleware(10, 50));
- 在創(chuàng)建數(shù)據(jù)庫Model時,將mongoose-pagination插件提供給postsSchema,如下所示:
postsSchema.plugin(mongoosePaginate);
const Posts = mongoose.model("Post", postsSchema);
- 獲取數(shù)據(jù)。調用paginate()函數(shù)以分頁的方式獲取請求的條目:
Posts.paginate(
{},
{
page: req.query.page,
limit: req.query.limit
},
(error, result) => {
if (error) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Internal server error");
return;
}
res.setHeader("Content-Type", "application/json");
res.send({
object: "contacts",
page_count: result.pages,
result: result
});
}
);
-
測試結果。如果每頁返回10條數(shù)據(jù),并想獲取到第2頁的數(shù)據(jù)。在地址欄中輸入localhost:8080/api?limit=10&page=2時,返回結果如下所示:
代碼分享。點擊這里查看和下載代碼。
5. 不足之處
要先轉換在Posts項目中,抓取數(shù)據(jù)保存到item.json中,才運行服務器。鄙人不才,不知在Package.json如何實現(xiàn)。
6.參考網(wǎng)站
- 在Node中使用JOSN:https://www.codementor.io/codementorteam/how-to-use-json-files-in-node-js-85hndqt32
- map方法:https://msdn.microsoft.com/library/ff679976(v=vs.94).aspx
- mongoose-paginate文檔:https://www.npmjs.com/package/mongoose-paginate
關注微信號:gh_93f4c7518be0
