-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWikipediaParser.js
549 lines (456 loc) · 17.2 KB
/
WikipediaParser.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
var wikiUtils = require('./WikipediaUtils');
var idWiki;
var request = require("request"); // easier HTTP library
var jsdom = require("jsdom"); // javascript implementaion of DOM, used here for scrapping web pges
const { JSDOM } = jsdom;
var infobosHtml;
var infoBioBoxChilds ;
var rowInfoTag;
var rowInfoText;
var TYPE_MAIN_TITLE = "MAIN_TITLE";
var TYPE_MAIN_IMAGE_URL = "MAIN_IMAGE_URL";
var TYPE_TITLE = "TITLE";
var TYPE_PARAGRAPH = "PARAGRAPH";
var TYPE_IMAGE = "IMAGE";
var TYPE_TABLE = "TABLE";
var TYPE_QUOTE = "QUOTE";
var TYPE_SUBTITLE = "SUBTITLE";
var TYPE_SUB_SUBTITLE = "SUB_SUBTITLE";
var TYPE_LIST = "LIST";
var TYPE_LIST_ITEM = "LIST_ITEM";
var LIST_TYPE_BULLETED = "BULLETED";
var LIST_TYPE_NUMBERED = "NUMBERED";
var LIST_TYPE_INDENTED = "INDENTED";
var IMAGE_SIDE_NONE = "NONE";
var IMAGE_SIDE_RIGHT = "RIGHT";
var IMAGE_SIDE_LEFT = "LEFT";
var elementsInfoBioBox = [];
var STATUS_ERROR_WIKI_API = "ERROR_WIKI_API";
var STATUS_ERROR_WIKI_NOT_REACHABLE = "ERROR_WIKI_NOT_REACHABLE";
var STATUS_EROROR_PARSING_FAILED = "ERROR_PARSING_FAILED";
module.exports =
{
fetchArticleElements: function(articleTitle)
{
return new Promise(function(resolve, reject)
{
articleTitle = encodeURIComponent(wikiUtils.optimizeArticleTitle(articleTitle));
console.log("[+] Sending requests to wikipedia API ...");
request({url: 'https://es.wikipedia.org/w/api.php?action=query&titles=' + articleTitle + '&utf8=1&&prop=pageimages&format=json&pithumbsize=500&redirects=', forever: true} , function (error, response, imageBody)
{
if (error || !isValidJSON(imageBody))
{
reject(STATUS_ERROR_WIKI_API);
return;
}
var wikiJSON = JSON.parse(imageBody);
var pages = wikiJSON["query"]["pages"];
var imageURL = null;
idWiki = Object.keys(pages)[0]
console.log(idWiki);
for (var key in pages)
{
articleTitle = pages[key]["title"];
if ("thumbnail" in pages[key])
{
if ("source" in pages[key]["thumbnail"])
{
imageURL = pages[key]["thumbnail"]["source"];
}
}
}
console.log("[+] Downloading wikipedia article \"" + articleTitle +"\"...");
request({url: 'https://es.wikipedia.org/?curid='+ idWiki + '?action=render', forever: true}, function (error, response, wikiBody)
{
if (error)
{
reject(STATUS_ERROR_WIKI_NOT_REACHABLE);
return;
}
var elements = parseWikipediaHTML(wikiBody, articleTitle, imageURL);
if (elements.length == 0)
{
reject(STATUS_EROROR_PARSING_FAILED);
return;
}
resolve(elements);
});
});
});
}
};
function parseWikipediaHTML(html, articleTitle, imageURL)
{
console.log("[+] Processing wikipedia response...");
var doc = new JSDOM(html).window.document;
var elements = [];
var mainElement = doc.getElementsByClassName("mw-parser-output")[0];
// push main title
elements.push(createTextElement(TYPE_MAIN_TITLE, articleTitle));
// push main image
var foundMainImage = false;
var mainImageElement = imageURL ? createMainImageElement(imageURL, null, null) : extractMainImageFromInfobox(mainElement);
if (mainImageElement != null)
{
elements.push(mainImageElement);
foundMainImage = true;
}
elements.push(createTextElement(TYPE_TITLE, "Introduction"));
// removing bad elements like '[Edit]' or 'Coordinates: ...'
let myPromise = new Promise(function(myResolve, myReject) {
var badElements = mainElement.getElementsByClassName("mw-editsection");
for (var x=0;x<badElements.length;x++) badElements[x].innerHTML = '';
});
myPromise.then(
function(value) {console.log(value);},
function(error) {console.log(error);}
);
var coordinatesElement = doc.getElementById("coordinates");
if (coordinatesElement) coordinatesElement.innerHTML = '';
var wikiElements = mainElement.childNodes;
console.log(`Wiki lenght es es ${wikiElements.length}`)
for (var i = 0; i < wikiElements.length; i++)
{
var currentElement = wikiElements[i];
var elementText = currentElement.textContent.trim();
switch (currentElement.tagName)
{
case "H2":
elements.push(createTextElement(TYPE_TITLE, elementText));
break;
case "H3":
elements.push(createTextElement(TYPE_SUBTITLE, elementText));
break;
case "H4":
case "H5":
case "H6":
elements.push(createTextElement(TYPE_SUB_SUBTITLE, elementText));
break;
case "P":
var paragraphParsedText = parseTextFromElement(currentElement);
if (paragraphParsedText.length > 0)
elements.push(createTextElement(TYPE_PARAGRAPH, paragraphParsedText));
break;
case "BLOCKQUOTE":
var quote = elementText;
var caption = null;
var captionElements = currentElement.getElementsByClassName("templatequotecite");
if (captionElements.length > 0)
{
caption = captionElements[0].textContent;
captionElements[0].innerHTML = "";
quote = currentElement.textContent.trim();
}
elements.push(createQuoteElement(quote, caption));
break;
case "UL":
case "OL":
case "DL":
var listElement = parseList(currentElement);
if (listElement["list_items"].length > 0)
elements.push(listElement);
break;
case "TABLE":
if (currentElement.className.startsWith("wikitable"))
{
elements.push(createTextElement(TYPE_TABLE, "Unsupported!"));
}
break;
}
if (currentElement.className == "thumb tright" || currentElement.className == "thumb tleft")
{
// looking for an image
var subImageNodes = currentElement.getElementsByClassName("image");
if (subImageNodes.length > 0)
{
if (subImageNodes[0].getElementsByTagName("img").length > 0)
{
// image found
var imageSide = currentElement.className == "thumb tright" ? IMAGE_SIDE_RIGHT : IMAGE_SIDE_LEFT;
var imageElement = parseImage(subImageNodes[0].getElementsByTagName("img")[0], imageSide);
if (imageElement.height >= 80 && imageElement.width >= 90 && !foundMainImage)
{
imageElement = createMainImageElement(imageElement.url, imageElement.height, imageElement.width);
foundMainImage = true;
}
elements.push(imageElement);
}
}
}
}
var infoboxes = mainElement.getElementsByClassName("infobox biography vcard");
infoboxes = infoboxes[0];
const hasInfo= new Promise((resolve, reject) => {
if (infoboxes.rows) {
var listaInfoList = extractInfobox(mainElement)
elements = elements.concat(listaInfoList);
resolve(elements)
} else {
const why = 'Still working on something else'
reject(why)
}
})
hasInfo.then(
function(value) {console.log(value);},
function(error) {console.log(error);}
);
//console.log(`lista length = ${elements.length}`);
//console.log(`lista info bio box = ${listaInfoList.length}`);
//console.log(`lista length despues de sumar = ${elements.length}`);
// console.log(elements[1])
// console.log(listaInfoList[1])
return elements;
}
function parseTextFromElement(element)
{
var parsedText = "";
var childs = element.childNodes;
var NODE_TEXT_TYPE = 3;
for (var j=0;j<childs.length;j++)
{
var child = childs[j];
if (child.nodeType == NODE_TEXT_TYPE || child.tagName == "B" || child.tagName == "SPAN" || child.tagName == "I")
{
parsedText += child.textContent;
}
else if (child.tagName == "A")
{
if (wikiUtils.isValidLink(child.href))
{
var linkStartMark = "[";
var linkEndMark = "]";
var linkSeperator = "|";
var shouldMarkLinks = false;
if (shouldMarkLinks)
{
parsedText += linkStartMark + child.textContent + linkSeperator + child.href.slice(child.href.lastIndexOf("/") + 1) + linkEndMark;
}
else
{
parsedText += child.textContent;
}
}
else
{
// not a real link
parsedText += child.textContent;
}
}
}
return parsedText;
}
function parseList(listElement)
{
var listItems = [];
var listType = LIST_TYPE_BULLETED;
switch (listElement.tagName)
{
case "UL":
case "OL":
listType = listElement.tagName == "UL" ? LIST_TYPE_BULLETED : LIST_TYPE_NUMBERED;
var childs = listElement.childNodes;
for (var j=0;j<childs.length;j++)
{
var child = childs[j];
if (child.tagName == "LI")
{
var itemText = parseTextFromElement(child).trim();
if (itemText.length > 0)
listItems.push(createListItemElement(itemText));
// find ULs inside list items
var liChilds = child.childNodes;
for (var x=0;x<liChilds.length;x++)
{
if (liChilds[x].tagName == "UL")
{
var subList = parseList(liChilds[x]);
listItems.push(subList);
}
}
}
}
break;
case "DL":
// description list. TODO
break;
}
return createListElement(listItems, listType);
}
function parseImage(imageElement, imageSide)
{
if (imageSide != IMAGE_SIDE_NONE && imageElement.tagName == "IMG")
{
var src = "https:" + imageElement.getAttribute("src");
var width = parseInt(imageElement.getAttribute("width"));
var height = parseInt(imageElement.getAttribute("height"));
var children = imageElement.parentNode.parentNode.getElementsByTagName("div");
var caption = "";
for (var i=0;i<children.length;i++)
{
var child = children[i];
if (child.getAttribute("class") == "thumbcaption")
caption = child.textContent.trim();
}
if (src != "")
{
return createImageElement(src, width, height, caption, imageSide);
}
}
return null;
}
function extractMainImageFromInfobox(mainElement)
{
var infoboxes = mainElement.getElementsByClassName("infobox");
if (infoboxes.length > 0)
{
var images = infoboxes[0].getElementsByTagName("img");
for (var i=0;i<images.length;i++)
{
var imageElement = images[i];
var src = "https:" + imageElement.getAttribute("src");
var width = parseInt(imageElement.getAttribute("width"));
var height = parseInt(imageElement.getAttribute("height"));
if (width > 90 && height > 80)
{
return createMainImageElement(src, height, width);
}
}
}
return null;
}
function extractInfobox(mainElement)
{
var infoboxes = mainElement.getElementsByClassName("infobox biography vcard");
infoboxes = infoboxes[0];
infobosHtml = infoboxes.rows;
// Prueba y error
console.log(infoboxes.rows.length);
console.log("con rows index cells ")
let x = infoboxes.rows[4].cells[0]
console.log(x.hasChildNodes());
console.log(x);
/*
console.log(infoboxes.rows[4].cells[0].textContent)
console.log(infoboxes.rows[4].cells[1].tagName)
console.log(infoboxes.rows[4].cells[1].textContent)
console.log("con rows index")
console.log(infoboxes.rows[4].tagName)
console.log(infoboxes.rows[4].textContent)
console.log("Con cells items")
console.log(infobosHtml.item(4).cells.item(0).tagName)
console.log(infobosHtml.item(4).cells.item(0).textContent)
*/
//27
//Length of the rows
for(let i=0;i<infobosHtml.length;i++){
// SInce its a table we need to access to the cells
for(let u=0; u<infobosHtml[i].cells.length; u++){
if (infobosHtml[i].cells.hasChildNodes){
let children = infobosHtml[i].cells.childNodes;
for (let p = 0; p < children.length; p++) {
console.log("Child items")
rowInfoTag = children[p]
console.log(rowInfoTag.nodeName)
rowInfoText = children[p].textContent
console.log(rowInfoText)
}
} else {
rowInfoTag = infobosHtml[i].cells[u].tagName
rowInfoText= infobosHtml[i].cells[u].textContent}
}
switch(rowInfoTag){
case "TH":
if(i == 0){
elementsInfoBioBox.push(createTextElement("MAIN_TITLE_INFO",rowInfoText))
console.log("Se agrego elemento Main")
break;
}
case "TH":
elementsInfoBioBox.push(createTextElement("TYPE_TITLE_INFO",rowInfoText))
console.log("Se agrego elemento Titulo")
break;
case "I":
case "P":
case "TD":
elementsInfoBioBox.push(createTextElement("TYPE_PARAGRAPH_INFO",rowInfoText))
console.log("Se agrego elemento Texto")
break;
}
//console.log(rowInfo.tagName);
//console.log(rowInfo.textContent);
}
return elementsInfoBioBox; }
/*
function AddInfoList(mainElement){
var infoBioBox = extractInfobox(mainElement);
var infoBioBoxChilds = infoBioBox [0];
var infoBioBoxChildsNow = infoBioBoxChilds.childNodes;
var InfoBioElements = infoBioBoxChildsNow;
console.log(`infoBioELements es ${InfoBioElements}`)
console.log(`infoBioELements lenght es ${InfoBioElements.length}`)
for (var i = 0;i < InfoBioElements.length; i++){
var currentElement = InfoBioElements.rows[i];
var elementText = currentElement.textContent.trim();
switch(currentElement.tagName){
case "th":
elementsInfoBioBox.push(createTextElement("MAIN_TITLE_INFO"),elementText)
console.log("Se agrego elemento Main")
break;
case "th":
elementsInfoBioBox.push(createTextElement("TYPE_TITLE_INFO"),elementText)
console.log("Se agrego elemento Titulo")
break;
case "td":
elementsInfoBioBox.push(createTextElement("TYPE_PARAGRAPH_INFO"),elementText)
console.log("Se agrego elemento Testo")
break;
}
} return elementsInfoBioBox;
}
*/
function thumbImageToFullImageURL(url)
{
return url.substring(0, url.lastIndexOf("/")).replace("/thumb/", "/");
}
function createTextElement(type, text)
{
return {"type": type, "text": text};
}
function createQuoteElement(text, caption)
{
if (caption != null)
return {"type": TYPE_QUOTE, "text": text, "caption": caption};
else
return {"type": TYPE_QUOTE, "text": text};
}
function createListElement(listItems, listType)
{
return {"type": TYPE_LIST, "list_items": listItems, "list_type": listType};
}
function createListItemElement(text)
{
return {"type": TYPE_LIST_ITEM, "text": text};
}
function createMainImageElement(thumbUrl, height, width)
{
if (height != null && width != null)
return {"type": TYPE_MAIN_IMAGE_URL, "url": thumbUrl, "width": width, "height": height, "full_url": thumbImageToFullImageURL(thumbUrl)};
else
return {"type": TYPE_MAIN_IMAGE_URL, "url": thumbUrl, "full_url": thumbImageToFullImageURL(thumbUrl)};
}
function createImageElement(url, width, height, caption, side)
{
return {"type": TYPE_IMAGE, "url": url, "width": width, "height": height, "caption": caption, "side": side};
}
function isValidJSON(str)
{
try
{
JSON.parse(str);
}
catch (e)
{
return false;
}
return true;
}