forked from Taiwan-Ebook-Lover/TaiwanEbookSearch-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkobo.js
More file actions
92 lines (72 loc) · 2.28 KB
/
Copy pathkobo.js
File metadata and controls
92 lines (72 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const rp = require('request-promise-native');
const cheerio = require('cheerio');
const url = require('url');
function searchBooks(keywords = '') {
// URL encode
keywords = encodeURIComponent(keywords);
const base = `https://www.kobo.com/tw/zh/search?Query=${keywords}`;
const options = {
uri: base,
resolveWithFullResponse: true,
simple: false,
gzip: true,
timeout: 10000,
};
return rp(options).then(response =>{
if (!(/^2/.test('' + response.statusCode))) {
// console.log('Not found or error in kobo!');
return [];
}
return _getBooks(cheerio.load(response.body), base);
}).catch(error => {
console.log(error.message);
return [];
});
}
// parse 找書
function _getBooks($, base = null) {
$list = $('ul[class=result-items] li');
let books = [];
// 找不到就是沒這書
if ($list.length === 0) {
// console.log('Not found in kobo!');
return books;
}
$list.each((i, elem) => {
// 從 script elem 拉 JSON data
const info = JSON.parse($(elem).children('.item-detail').children('script').html());
// 若有副標題,併入主標題
let title = info.name;
if (info.alternativeHeadline) {
title += ` - ${info.alternativeHeadline}`;
}
// 合併作者成一個陣列
let authors = [];
for (let item of info.author) {
authors = authors.concat(item.name.split('、'));
}
// 價格要先檢查是否為免費
const $priceField = $(elem).children('.item-detail').children('.item-info').children('.price');
let price = 0;
if (!$priceField.hasClass('free')) {
price = parseFloat($priceField.children('span').children('span').first().text().replace(/NT\$|,|\s/g, ''));
}
books[i] = {
id: info.isbn,
// 圖片網址為相對位置,需要 resolve
thumbnail: url.resolve(base, info.thumbnailUrl),
title,
link: info.url,
priceCurrency: $(elem).children('.item-detail').children('.item-info').children('.price').children('span').children('.currency').text(),
price,
about: info.description ? `${info.description} ...` : null,
// publisher
};
// 作者群有資料才放
if (authors.length > 0) {
books[i].authors;
}
});
return books;
}
exports.searchBooks = searchBooks;