/
pos_spider.py
428 lines (366 loc) · 13.1 KB
/
pos_spider.py
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
# -*- coding: utf-8 -*-
#
# This file is part of hepcrawl.
# Copyright (C) 2016, 2017, 2019 CERN.
#
# hepcrawl is a free software; you can redistribute it and/or modify it
# under the terms of the Revised BSD License; see LICENSE file for
# more details.
"""Spider for POS."""
from __future__ import absolute_import, division, print_function
import os
import re
from scrapy import Request, Selector
from six.moves.urllib.parse import quote, urljoin
from . import StatefulSpider
from ..dateutils import create_valid_date
from ..items import HEPRecord
from ..loaders import HEPLoader
from ..utils import (
ParsedItem,
get_first,
get_licenses,
strict_kwargs,
)
DEFAULT_BASE_URL = 'https://pos.sissa.it'
DEFAULT_BASE_CONFERENCE_PAPER_URL = (
DEFAULT_BASE_URL + '/contribution?id='
)
DEFAULT_BASE_PROCEEDINGS_URL = (
DEFAULT_BASE_URL + '/cgi-bin/reader/conf.cgi?confid='
)
class PoSExtractionException(Exception):
pass
class POSSpider(StatefulSpider):
"""POS/Sissa crawler.
From PoS we create two types of records, a conference paper record, and a
conference proceedings record.
The bulk of the records comes from oaiharvest, and this spider crawls the
files generated by it.
For the conference paper record we have to scrape also the html page of the
record on the PoS website to get the pdf link. (see
`DEFAULT_BASE_CONFERENCE_PAPER_URL`)
Then, from that same page, we get the internal conference id.
With that conference id, then we scrape the conference proceedings page,
and extract the information to create the proceedings record. (see
`DEFAULT_BASE_PROCEEDINGS_URL`)
To do that and because each needs the information of the previous, the
spider must use the callbacks system provided by scrapy through the
:class:`scrapy.html.response.Response` callback parameter, and chain the
parser functions.
The deduplication of the conference proceedings papers is left for the
`HepcrawlCrawlOnceMiddleware` middleware.
Example:
::
$ scrapy crawl PoS \\
-a "source_file=file://$PWD/tests/unit/responses/pos/sample_pos_record.xml"
"""
name = 'pos'
@strict_kwargs
def __init__(
self,
source_file=None,
base_conference_paper_url=DEFAULT_BASE_CONFERENCE_PAPER_URL,
base_proceedings_url=DEFAULT_BASE_PROCEEDINGS_URL,
**kwargs
):
super(POSSpider, self).__init__(**kwargs)
self.source_file = source_file
self.base_conference_paper_url = base_conference_paper_url
self.base_proceedings_url = base_proceedings_url
def start_requests(self):
yield Request(self.source_file)
def parse(self, response):
self.logger.info('Got record from: {response.url}'.format(**vars()))
response.selector.remove_namespaces()
record_xml_selectors = response.selector.xpath('.//record')
for record_xml_selector in record_xml_selectors:
yield self.get_conference_paper_page_request(
xml_selector=record_xml_selector,
)
def get_conference_paper_page_request(self, xml_selector, meta=None):
"""Gets the conference paper html page, for the pdf link for the
conference paper, and later the internal conference id.
"""
meta = meta or {}
identifier = xml_selector.xpath(
'.//metadata/pex-dc/identifier/text()'
).extract_first()
conference_paper_url = "{0}{1}".format(
self.base_conference_paper_url,
identifier,
)
meta['xml_record'] = xml_selector.extract()
# the meta parameter will be passed over to the callback as a property
# in the response parameter
return Request(
url=conference_paper_url,
callback=self.parse_conference_paper,
meta=meta
)
def parse_conference_paper(self, response):
self.logger.info(
'Parsing conference paper from: {response.url}'.format(**vars())
)
xml_record = response.meta.get('xml_record')
conference_paper_url = response.url
conference_paper_pdf_url = self._get_conference_paper_pdf_url(
conference_paper_page_html=response.body,
)
parsed_conference_paper = self.build_conference_paper_item(
xml_record=xml_record,
conference_paper_url=conference_paper_url,
conference_paper_pdf_url=conference_paper_pdf_url,
)
yield parsed_conference_paper
# prepare next callback step
response.meta['html_record'] = response.body
yield self.get_conference_proceedings_page_request(
meta=response.meta,
)
def get_conference_proceedings_page_request(self, meta):
"""Gets the conference proceedings page, using the indernal conference
id from the record html page retrieved before.
"""
if not meta.get('html_record'):
raise PoSExtractionException(
'PoS conference paper page was empty, current meta:\n%s' % meta
)
proceedings_page_url = self._get_proceedings_page_url(
page_html=meta.get('html_record'),
)
page_selector = Selector(
text=meta.get('xml_record'),
type='xml',
)
page_selector.remove_namespaces()
pos_id = page_selector.xpath(
".//metadata/pex-dc/identifier/text()"
).extract_first()
meta['pos_id'] = pos_id
return Request(
url=proceedings_page_url,
meta=meta,
callback=self.parse_conference_proceedings,
)
def parse_conference_proceedings(self, request):
parsed_conference_proceedings = self.build_conference_proceedings_item(
proceedings_page_html=request.body,
pos_id=request.meta['pos_id'],
)
yield parsed_conference_proceedings
def _get_proceedings_page_url(self, page_html):
page_selector = Selector(
text=page_html,
type="html"
)
internal_url = page_selector.xpath(
"//a[not(contains(text(),'pdf'))]/@href",
).extract_first()
proceedings_internal_id = internal_url.split('/')[1]
return '{0}{1}'.format(
self.base_proceedings_url,
proceedings_internal_id,
)
def build_conference_paper_item(
self,
xml_record,
conference_paper_url,
conference_paper_pdf_url,
):
selector = Selector(
text=xml_record,
type="xml"
)
selector.remove_namespaces()
record = HEPLoader(
item=HEPRecord(),
selector=selector
)
license_text = selector.xpath(
'.//metadata/pex-dc/rights/text()'
).extract_first()
record.add_value('license', get_licenses(license_text=license_text))
date, year = self._get_date(selector=selector)
record.add_value('date_published', date)
record.add_value('journal_year', year)
identifier = selector.xpath(
".//metadata/pex-dc/identifier/text()"
).extract_first()
record.add_value(
'journal_title',
self._get_journal_title(pos_ext_identifier=identifier),
)
record.add_value(
'journal_volume',
self._get_journal_volume(pos_ext_identifier=identifier),
)
record.add_value(
'journal_artid',
self._get_journal_artid(pos_ext_identifier=identifier),
)
record.add_xpath('title', '//metadata/pex-dc/title/text()')
record.add_xpath('source', '//metadata/pex-dc/publisher/text()')
record.add_value(
'external_system_numbers',
self._get_ext_systems_number(selector=selector),
)
record.add_value('language', self._get_language(selector=selector))
record.add_value('authors', self._get_authors(selector=selector))
record.add_value('collections', ['conferencepaper'])
record.add_value('urls', [conference_paper_url])
record.add_value(
'documents',
self.get_documents(
path=conference_paper_pdf_url,
),
)
parsed_item = ParsedItem(
record=record.load_item(),
record_format='hepcrawl',
)
return parsed_item
def build_conference_proceedings_item(
self,
proceedings_page_html,
pos_id,
):
selector = Selector(
text=proceedings_page_html,
type='html',
)
selector.remove_namespaces()
record = HEPLoader(
item=HEPRecord(),
selector=selector
)
record.add_value('collections', ['proceedings'])
record.add_value(
'title',
self._get_proceedings_title(selector=selector),
)
record.add_value(
'subtitle',
self._get_proceedings_date_place(selector=selector),
)
record.add_value('journal_title', 'PoS')
record.add_value(
'journal_volume',
self._get_journal_volume(pos_ext_identifier=pos_id),
)
parsed_proceeding = ParsedItem(
record=record.load_item(),
record_format='hepcrawl',
)
return parsed_proceeding
def _get_conference_paper_pdf_url(self, conference_paper_page_html):
selector = Selector(
text=conference_paper_page_html,
type='html',
)
conference_paper_pdf_relative_url = selector.xpath(
"//a[contains(text(),'pdf')]/@href",
).extract_first()
if not conference_paper_pdf_relative_url:
raise PoSExtractionException(
(
'Unable to get the conference paper pdf url from the html:'
'\n%s'
) % conference_paper_page_html
)
return urljoin(
self.base_conference_paper_url,
conference_paper_pdf_relative_url,
)
def _get_proceedings_url(self, response):
internal_url = response.selector.xpath(
"//a[not(contains(text(),'pdf'))]/@href",
).extract_first()
proceedings_identifier = internal_url.split('/')[1]
return '{0}{1}'.format(
self.base_proceedings_url,
proceedings_identifier,
)
@staticmethod
def get_documents(path):
return [
{
'key': os.path.basename(path),
'url': quote(path, safe=':/'),
'original_url': quote(path, safe=':/'),
'hidden': True,
'fulltext': True,
},
]
@staticmethod
def _get_language(selector):
language = selector.xpath(
".//metadata/pex-dc/language/text()"
).extract_first()
return language if language != 'en' else None
@staticmethod
def _get_journal_title(pos_ext_identifier):
return re.split('[()]', pos_ext_identifier)[0]
@staticmethod
def _get_journal_volume(pos_ext_identifier):
return re.split('[()]', pos_ext_identifier)[1]
@staticmethod
def _get_journal_artid(pos_ext_identifier):
return re.split('[()]', pos_ext_identifier)[2]
@staticmethod
def _get_ext_systems_number(selector):
return [
{
'institute': 'pos',
'value': selector.xpath(
'.//identifier/text()'
).extract_first()
},
]
@staticmethod
def _get_date(selector):
full_date = selector.xpath(
".//metadata/pex-dc/date/text()"
).extract_first()
date = create_valid_date(full_date)
year = int(date[0:4])
return date, year
@staticmethod
def _get_authors(selector):
"""Get article authors."""
authors = []
creators = selector.xpath('.//metadata/pex-dc/creator')
for creator in creators:
auth_dict = {}
author = Selector(text=creator.extract())
auth_dict['raw_name'] = get_first(
author.xpath('.//name//text()').extract(),
default='',
)
for affiliation in author.xpath(
'.//affiliation//text()'
).extract():
if 'affiliations' in auth_dict:
auth_dict['affiliations'].append(
{
'value': affiliation
}
)
else:
auth_dict['affiliations'] = [
{
'value': affiliation
},
]
if auth_dict:
authors.append(auth_dict)
return authors
@staticmethod
def _get_proceedings_title(selector):
return 'Proceedings, ' + selector.xpath('//h1/text()').extract_first()
@staticmethod
def _get_proceedings_date_place(selector):
date_place = selector.xpath(
"//div[@class='conference_date']/text()"
).extract()
return ''.join(date_place)