forked from l0o0/translators_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Douban.js
468 lines (412 loc) · 13.4 KB
/
Douban.js
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
{
"translatorID": "fc353b26-8911-4c34-9196-f6f567c93901",
"label": "Douban",
"creator": "不是船长<[email protected]>,Ace Strong<[email protected]>",
"target": "^https?://(www|book)\\.douban\\.com/(subject|doulist|people/[a-zA-Z._]*/(do|wish|collect)|.*?status=(do|wish|collect)|group/[0-9]*?/collection|tag)",
"minVersion": "2.0rc1",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2021-04-09 07:09:26"
}
/*
Douban Translator
Copyright (C) 2009-2010 TAO Cheng, [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// #######################
// ##### Sample URLs #####
// #######################
/*
* The starting point for an search is the URL below.
* In testing, I tried the following:
*
* - A search listing of books
* - A book page
* - A doulist page
* - A do page
* - A wish page
* - A collect page
*/
// http://book.douban.com/
function detectWeb(doc, url) {
var pattern = /subject_search|doulist|people\/[a-zA-Z._]*?\/(?:do|wish|collect)|.*?status=(?:do|wish|collect)|group\/[0-9]*?\/collection|tag/;
if (pattern.test(url)) {
return "multiple";
}
else {
return "book";
}
}
function detectTitles(doc, url) {
var pattern = /\.douban\.com\/tag\//;
if (pattern.test(url)) {
return ZU.xpath(doc, '//div[@class="info"]/h2/a');
} else {
return ZU.xpath(doc, '//div[@class="title"]/a');
}
}
function doWeb(doc, url) {
var articles = [];
let r = /douban.com\/url\//;
if (detectWeb(doc, url) == "multiple") {
// also searches but they don't work as test cases in Scaffold
// e.g. https://book.douban.com/subject_search?search_text=Murakami&cat=1001
var items = {};
// var titles = ZU.xpath(doc, '//div[@class="title"]/a');
var titles = detectTitles(doc, url);
var title;
for (let i = 0; i < titles.length; i++) {
title = titles[i];
// Zotero.debug({ href: title.href, title: title.textContent });
if (r.test(title.href)) { // Ignore links
continue;
}
items[title.href] = title.textContent;
}
Zotero.selectItems(items, function (items) {
if (!items) {
return;
}
for (var i in items) {
articles.push(i);
}
ZU.processDocuments(articles, scrapeAndParse);
});
}
else {
scrapeAndParse(doc, url);
}
}
function trimTags(text) {
return text.replace(/(<.*?>)/g, "");
}
// #############################
// ##### Scraper functions #####
// #############################
function scrapeAndParse(doc, url) {
// Z.debug({ url })
ZU.doGet(url, function (page) {
// Z.debug(page)
var pattern, extra;
// 类型 & URL
var itemType = "book";
var newItem = new Zotero.Item(itemType);
// Zotero.debug(itemType);
newItem.url = url;
// 评分
let dbScore = ZU.xpathText(doc, '//*[@id="interest_sectl"]/div[1]/div[2]/strong')
dbScore= dbScore.trim()
if(dbScore===" "||dbScore===""){
dbScore = "?"
}
// 评价人数
let commentNum = ZU.xpathText(doc, '//*[@id="interest_sectl"]/div[1]/div[2]/div/div[2]/span/a/span')
// 副标题
pattern = /<span [^>]*?>副标题:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var subTitle = pattern.exec(page)[1].trim()
}
// 原作名
pattern = /<span [^>]*?>原作名:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var originalTitle = pattern.exec(page)[1].trim()
}
// 标题
let titleTemp = ""
pattern = /<h1>([\s\S]*?)<\/h1>/;
if (pattern.test(page)) {
var title = pattern.exec(page)[1];
title = ZU.trim(trimTags(title))
let originalTitlePre = " #"
if(!originalTitle){ // 当没有原名时,使用空字符
originalTitlePre = ""
}
if(title === subTitle){ // 判断下副标题与标题一样否,避免重复
extra = "👩⚖️" + commentNum+";"+"🔟"+dbScore+originalTitlePre+originalTitle
} else {
extra = "《"+title+" - "+subTitle+"》;"+ "👩⚖️" + commentNum+";"+"🔟"+dbScore+originalTitlePre+originalTitle
}
extra = extra.replace(/( - )?undefined/g,"").replace("null","0")
extra += ';'
newItem.title = title;
}
// 短标题
newItem.shortTitle = "《"+title+"》"
// 目录
let catalogueList = ZU.xpath(doc, "//div[@class='indent' and contains(@id, 'dir_') and contains(@id, 'full')]")
let catalogue = ""
if(catalogueList.length>0){
catalogue = "<h1>#摘录-《"+title+"》目录</h1>\n"+catalogueList[0].innerHTML
newItem.notes.push({note:catalogue})
}
// 作者
page = page.replace(/\n/g, "");
page = page.replace(/ /g,"")
// Z.debug(page)
// 豆瓣里作者一栏及其不规范,这里使用多正则匹配更多情况,提高兼容性
let regexp = new RegExp() // 这里要把类型定义为RegExp,否则下面赋值后test(page)会失败
let regexp2 = new RegExp()
let regexp3 = new RegExp()
regexp = /<span>\s*<span[^>]*?>\s*作者<\/span>:(.*?)<\/span>/;
regexp2 = /<span class="pl">作者:<\/span>\s*?<a href="https:\/\/book\.douban\.com\/author\/\d+\/">\s*?\S*?\s*?\S*?<\/a>\s*?<br>/
regexp3 = /<span class="pl">作者:<\/span>\s*?<a href="https:\/\/book\.douban\.com\/author\/\d+\/">\s*?\S*?\s*?\S*?<\/a>\s+\//
if (regexp2.test(page)) {
regexp = regexp2
} else if(regexp3.test(page)){
regexp = regexp3
}
if (regexp.test(page)) {
var authorNames = trimTags(regexp.exec(page)[0]);
pattern = /(\[.*?\]|\(.*?\)|(.*?))/g;
authorNames = authorNames.replace(pattern, "").split("/");
// 国家
let country = RegExp.$1
country = country.replace("美国","美")
country = country.match(/[一-龥]+/g)
if(country===null){
country = [" "]
}
// Zotero.debug(authorNames);
let firstNameList = [] // 作者名列表
let lastNameList = [] // 作者姓列表
for (let i = 0; i < authorNames.length; i++) {
let useComma = true;
pattern = /[A-Za-z]/;
if (pattern.test(authorNames[i])) {
// 外文名
pattern = /,/;
if (!pattern.test(authorNames[i])) {
useComma = false;
}
}
// 实现欧美作者姓与名分开展示
let patt1 = new RegExp("·.+\.+")
let authorNameTemp = ""
let ming = ""
let xing = ""
authorNames[i] = authorNames[i].replace(/作者:?( )?\s+/g, "")
if(authorNames[i].indexOf(".")!= -1){ // 名字中带.的 如:斯蒂芬·D.埃平格
authorNameTemp = authorNames[i].trim().split(".")
xing = authorNameTemp.pop() // 取数组最后一个值作为名
ming = authorNameTemp.join("·") // 姓氏
} else {
authorNames[i] =authorNames[i].replace(/•/g,"·") // 替换中文•分隔符为英文·
authorNameTemp = authorNames[i].trim().split("·")
xing = authorNameTemp.pop()
ming = authorNameTemp.join("·")
}
if(country[i]){
country = country[i].replace(/<\/a>/g,"")
}
if(country!=" "){
country = "["+country+"]"
}
firstNameList.push(country+ming)
lastNameList.push(xing)
newItem.creators.push({firstName:firstNameList[i],lastName:lastNameList[i], creatorType:"author", fieldMode:true});
// newItem.creators.push(Zotero.Utilities.cleanAuthor(
// Zotero.Utilities.trim(authorNames[i]),
// "author", useComma));
}
}
// 译者
pattern = /<span>\s*<span [^>]*?>\s*译者<\/span>:(.*?)<\/span>/;
if (pattern.test(page)) {
var translatorNames = trimTags(pattern.exec(page)[1]);
pattern = /(\[.*?\])/g;
translatorNames = translatorNames.replace(pattern, "").split("/");
// Zotero.debug(translatorNames);
for (let i = 0; i < translatorNames.length; i++) {
let useComma = true;
pattern = /[A-Za-z]/;
if (pattern.test(translatorNames[i])) {
// 外文名
useComma = false;
}
newItem.creators.push(ZU.cleanAuthor(
ZU.trim(translatorNames[i]),
"translator", useComma));
}
}
// ISBN
pattern = /<span [^>]*?>ISBN:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var isbn = pattern.exec(page)[1];
newItem.ISBN = ZU.trim(isbn);
// Zotero.debug("isbn: "+isbn);
}
// 页数
pattern = /<span [^>]*?>页数:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var numPages = pattern.exec(page)[1];
newItem.numPages = ZU.trim(numPages);
// Zotero.debug("numPages: "+numPages);
}
// 出版社
pattern = /<span [^>]*?>出版社:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var publisher = pattern.exec(page)[1];
newItem.publisher = ZU.trim(publisher);
// Zotero.debug("publisher: "+publisher);
}
// 定价
pattern = /<span [^>]*?>定价:(.*?)<\/span>(.*?)<br\/?>/;
var price;
if (pattern.test(page)) {
var price = pattern.exec(page)[2];
// price = "60"
let prefix = price.match(/^((?!(\d+\.?\d*)).)*/g)[0] // 正则匹配前缀,如USD,CAD
price = price.match(/(\d+\.?\d*)/g)[0]
// 小数点后2为保持
let numPrice = Number(price)
numPrice = numPrice.toFixed(2)
// 车同轨书同文,一统金额样式
if(prefix===""||prefix===" "||prefix.includes("CNY")){
price = numPrice+" 元;";
} else {
price = prefix+numPrice + ';';
}
}
// 丛书
pattern = /<span [^>]*?>丛书:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var series = trimTags(pattern.exec(page)[0]);
series = series.split("ISBN")[0].replace("丛书:", "");
newItem.series = ZU.trim(series);
// Zotero.debug("series: "+series);
}
// 出版年
pattern = /<span [^>]*?>出版年:<\/span>(.*?)<br\/>/;
if (pattern.test(page)) {
var date = pattern.exec(page)[1];
newItem.date = ZU.trim(date);
// Zotero.debug("date: "+date);
}
//补全0
function completeDate(value) {
return value < 10 ? "0"+value:value;
}
// 其他
newItem.extra = extra + price;
// 标签
var tags = ZU.xpath(doc, '//div[@id="db-tags-section"]/div[@class="indent"]/span/a[contains(@class, "tag") ]');
for (let i in tags) {
newItem.tags.push(tags[i].text);
}
// 作者简介
let authorInfoList = ZU.xpath(doc, "//span[text()='作者简介']/parent::h2/following-sibling::div//div[@class='intro']")
// 这里会获取平级的元素,当有多个时(有展开全部按钮)取最后一个
let authorInfo = ""
let authorInfotwo = ""
if(authorInfoList.length>0){
authorInfo = authorInfoList[authorInfoList.length-1].innerHTML
// 正则提取<p>标签里面的元素,并添加换行
authorInfo = authorInfo.match(/<[a-zA-Z]+.*?>([\s\S]*?)<\/[a-zA-Z]+.*?>/g)
for(i=0;i<authorInfo.length;i++){
authorInfo[i] = authorInfo[i].match(/<[a-zA-Z]+.*?>([\s\S]*?)<\/[a-zA-Z]+.*?>/g)
authorInfotwo = authorInfotwo+RegExp.$1+"\n"
}
}
// 内容简介
// 获取展开全部按钮里面的内容
let contentInfoList = ZU.xpath(doc, "//span[text()='内容简介']/parent::h2/following-sibling::div[@id='link-report']//div[@class='intro']")
let contentInfo = ""
let contentInfoTwo = ""
if(contentInfoList.length>0){
contentInfo = contentInfoList[contentInfoList.length-1].innerHTML
contentInfo = contentInfo.match(/<[a-zA-Z]+.*?>([\s\S]*?)<\/[a-zA-Z]+.*?>/g)
for(i=0;i<contentInfo.length;i++){
contentInfo[i] = contentInfo[i].match(/<[a-zA-Z]+.*?>([\s\S]*?)<\/[a-zA-Z]+.*?>/g)
contentInfoTwo = contentInfoTwo+RegExp.$1+"\n"
}
}
let abstractNoteTemp = "作者简介:"+"\n"+authorInfotwo+"\n"+
"内容简介:"+"\n"+contentInfoTwo
newItem.abstractNote = abstractNoteTemp
newItem.complete();
});
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "https://book.douban.com/subject/1355643/",
"items": [
{
"itemType": "book",
"title": "Norwegian Wood",
"creators": [
{
"firstName": "Haruki",
"lastName": "Murakami",
"creatorType": "author"
},
{
"firstName": "Jay",
"lastName": "Rubin",
"creatorType": "translator"
}
],
"date": "2003",
"ISBN": "9780099448822",
"abstractNote": "When he hears her favourite Beatles song, Toru Watanabe recalls his first love Naoko, the girlfriend of his best friend Kizuki. Immediately he is transported back almost twenty years to his student days in Tokyo, adrift in a world of uneasy friendships, casual sex, passion, loss and desire - to a time when an impetuous young woman called Midori marches into his life and he has ..., (展开全部)",
"libraryCatalog": "Douban",
"numPages": "389",
"publisher": "Vintage",
"url": "https://book.douban.com/subject/1355643/",
"attachments": [],
"tags": [
{
"tag": "HarukiMurakami"
},
{
"tag": "小说"
},
{
"tag": "挪威森林英文版"
},
{
"tag": "日本"
},
{
"tag": "日本文学"
},
{
"tag": "村上春树"
},
{
"tag": "英文原版"
},
{
"tag": "英文版"
}
],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "https://www.douban.com/doulist/120664512/",
"items": "multiple"
},
{
"type": "web",
"url": "https://book.douban.com/tag/认知心理学?type=S",
"items": "multiple"
}
]
/** END TEST CASES **/