Skip to content

Commit 8862d53

Browse files
committed
[Wikipedia] Get correct date for specific revision. Wrong abstract :(
Can't find a way to get the abstract for specific revision, so it corresponds to the most recent version. There's rvprop=content&rvparse=true&rvsection=0, but that includes the info box. Scraping from page is not very reliable. See test case for Россия
1 parent 149956a commit 8862d53

File tree

1 file changed

+32
-18
lines changed

1 file changed

+32
-18
lines changed

Wikipedia.js

+32-18
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"inRepository": true,
1010
"translatorType": 4,
1111
"browserSupport": "gcsibv",
12-
"lastUpdated": "2015-02-16 03:56:10"
12+
"lastUpdated": "2015-02-16 04:51:10"
1313
}
1414

1515
/**
@@ -31,13 +31,14 @@
3131
*/
3232

3333
function detectWeb(doc, url) {
34-
if(ZU.xpathText(doc, '//h1[@id="firstHeading"]'))
34+
if(doc.getElementById('firstHeading')) {
3535
return 'encyclopediaArticle';
36+
}
3637
}
3738

3839
function doWeb(doc, url) {
3940
var item = new Zotero.Item('encyclopediaArticle');
40-
item.title = ZU.xpathText(doc, '//h1[@id="firstHeading"]');
41+
item.title = ZU.trimInternal(doc.getElementById('firstHeading').textContent);
4142

4243
/* Removing the creator and publisher. Wikipedia is pushing the creator in their own
4344
directions on how to cite http://en.wikipedia.org/w/index.php?title=Special%3ACite&page=Psychology
@@ -69,9 +70,10 @@ function doWeb(doc, url) {
6970
}
7071

7172
item.url = ZU.xpathText(doc, '//li[@id="t-permalink"]/a/@href');
73+
var revID;
7274
if(item.url) {
73-
item.extra = 'Page Version ID: ' +
74-
item.url.match(/[&?]oldid=(\d+)/)[1];
75+
revID = item.url.match(/[&?]oldid=(\d+)/)[1];
76+
item.extra = 'Page Version ID: ' + revID;
7577
item.url = doc.location.protocol + '//' + doc.location.hostname
7678
+ item.url;
7779
} else {
@@ -86,21 +88,33 @@ function doWeb(doc, url) {
8688
});
8789

8890
item.language = doc.documentElement.lang;
89-
90-
var abs = ZU.xpathText(doc, '//div[@id="mw-content-text"]/p[1]', null, '');
91-
if(abs) item.abstractNote = ZU.trimInternal(abs);
92-
91+
9392
//last modified date is hard to get from the page because it is localized
94-
var pageInfoURL = '/w/api.php?action=query&prop=info&format=json&' +
95-
'inprop=url%7Cdisplaytitle&titles=' +
96-
item.title;
93+
var pageInfoURL = '/w/api.php?action=query&format=json'
94+
+ '&inprop=url%7Cdisplaytitle'
95+
+ '&exintro=true&explaintext=true' // Intro section in plain text
96+
+ '&prop=info%7Cextracts'
97+
+ (revID // Different if we want a specific revision (this should be the general case)
98+
? '%7Crevisions&rvprop=timestamp&revids=' + encodeURIComponent(revID)
99+
: '&titles=' + encodeURIComponent(item.title)
100+
);
97101
ZU.doGet(pageInfoURL, function(text) {
98102
var retObj = JSON.parse(text);
99103
if(retObj && !retObj.query.pages['-1']) {
100104
var pages = retObj.query.pages;
101105
for(var i in pages) {
102-
item.date = pages[i].touched;
106+
if (pages[i].revisions) {
107+
item.date = pages[i].revisions[0].timestamp;
108+
} else {
109+
item.date = pages[i].touched;
110+
}
111+
103112
item.title = pages[i].displaytitle;
113+
114+
// Note that this is the abstract for the latest revision,
115+
// not necessarily the revision that is being queried
116+
item.abstractNote = pages[i].extract;
117+
104118
//we should never have more than one page returned,
105119
//but break just in case
106120
break;
@@ -118,8 +132,8 @@ var testCases = [
118132
"itemType": "encyclopediaArticle",
119133
"title": "Россия",
120134
"creators": [],
121-
"date": "2015-02-16T02:48:25Z",
122-
"abstractNote": "Координаты: 66°25′ с. ш. 94°15′ в. д. / 66.417° с. ш. 94.250° в. д. / 66.417; 94.250 (G) (O)",
135+
"date": "2012-04-06T20:11:32Z",
136+
"abstractNote": "Росси́я (от греч. Ρωσία — Русь; официально Росси́йская Федера́ция или Росси́я, на практике используется также сокращение РФ) — государство в Восточной Европе и Северной Азии. Население — 146 270 033 чел. (2015), территория — 17 125 187 км². Занимает первое место в мире по территории и девятое место по численности населения.\nСтолица — Москва. Государственный язык — русский.\nСмешанная республика федеративного устройства. В мае 2012 года пост президента занял Владимир Путин, председателя правительства — Дмитрий Медведев.\nВ составе Российской Федерации находятся 85 субъектов, 46 из которых именуются областями, 22 — республиками, 9 — краями, 3 — городами федерального значения, 4 — автономными округами и 1 — автономной областью.\nРоссия граничит с девятнадцатью странами (самый большой показатель в мире), включая две частично признанных, из них по суше со следующими государствами: Норвегией, Финляндией, Эстонией, Латвией, Литвой, Польшей, Белоруссией, Украиной, Абхазией, Грузией, Южной Осетией, Азербайджаном, Казахстаном, КНР, КНДР, Монголией, по морю с Турцией, Японией и США.\nОтличается значительным этнокультурным разнообразием. Бо́льшая часть (около 75 %) населения относит себя к православию, что делает Россию страной с самым многочисленным православным населением в мире.\nПо данным Всемирного банка, объём ВВП по ППС за 2014 год составил $3,461 трлн ($24,120 на человека). Денежная единица — российский рубль (усреднённый курс за 2014 год — 36 рублей за 1 доллар США).\nЯвляется великой державой и энергетической сверхдержавой — кандидатом-сверхдержавой, постоянный член Совета безопасности ООН. Одна из ведущих космических держав мира, обладает ядерным оружием и средствами его «доставки».\nПосле распада СССР в конце 1991 года Российская Федерация была признана международным сообществом как государство-продолжатель СССР в вопросах ядерного потенциала СССР, внешнего долга СССР, собственности СССР за рубежом, а также членства в Совете Безопасности ООН. Россия состоит в ряде международных организаций — ООН, ОБСЕ, Совет Европы, ЕАЭС, СНГ, ОЧЭС, ОДКБ, ВТО, ВФП, ЦАС, ШОС, АТЭС, БРИКС, МОК, ISO и других.",
123137
"encyclopediaTitle": "Википедия",
124138
"extra": "Page Version ID: 43336101",
125139
"language": "ru",
@@ -147,8 +161,8 @@ var testCases = [
147161
"itemType": "encyclopediaArticle",
148162
"title": "Zotero",
149163
"creators": [],
150-
"date": "2015-02-14T13:05:20Z",
151-
"abstractNote": "Zotero (/[unsupported input]zoʊˈtɛroʊ/) is free, open source reference management software to manage bibliographic data and related research materials (such as PDFs). Notable features include web browser integration, online syncing, generation of in-text citations, footnotes and bibliographies, as well as integration with the word processors Microsoft Word, LibreOffice, OpenOffice.org Writer and NeoOffice. It is produced by the Center for History and New Media of George Mason University (GMU).",
164+
"date": "2012-04-03T14:41:27Z",
165+
"abstractNote": "Zotero /zoʊˈtɛroʊ/ is free and open-source reference management software to manage bibliographic data and related research materials (such as PDF files). Notable features include web browser integration, online syncing, generation of in-text citations, footnotes and bibliographies, as well as integration with the word processors Microsoft Word, LibreOffice, OpenOffice.org Writer and NeoOffice. It is produced by the Center for History and New Media of George Mason University (GMU).",
152166
"encyclopediaTitle": "Wikipedia, the free encyclopedia",
153167
"extra": "Page Version ID: 485342619",
154168
"language": "en",
@@ -176,7 +190,7 @@ var testCases = [
176190
"itemType": "encyclopediaArticle",
177191
"title": "Wikipedia:Article wizard",
178192
"creators": [],
179-
"date": "2015-02-10T14:18:16Z",
193+
"date": "2015-02-10T10:51:06Z",
180194
"encyclopediaTitle": "Wikipedia, the free encyclopedia",
181195
"extra": "Page Version ID: 646481896",
182196
"language": "en",

0 commit comments

Comments
 (0)