nosdeputes_importer 6.58 KB
Newer Older
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Strongly based on https://github.com/LaboratoireCitoyen/FranceData

import gzip, json, os, sys, re
from urllib import quote

import scrapy
from scrapy.dupefilters import RFPDupeFilter
from scrapy import signals
from scrapy.exceptions import DropItem
from scrapy.utils.serialize import ScrapyJSONEncoder
from scrapy.crawler import CrawlerProcess
from scrapy import Request
from scrapy.spiders import CrawlSpider

def get_photo_url(rep_url, kind):
    res = rep_url.rsplit('/', 1)
    res.insert(-1, kind + '/photo')
    return '/'.join(res)

class URLScreenFilter(RFPDupeFilter):
    urls = set()

    def request_seen(self, request):
        if not request.url.endswith('#nodedupe') and request.url in self.urls:
            return True
        else:
            self.urls.add(request.url)
            return False

class FrancedataPipeline(object):
    has_items = False
    urls = set()

    @classmethod
    def from_crawler(cls, crawler):
        pipeline = cls(crawler.settings.get('OUTPUT_FILE'))
        crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
        crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
        return pipeline

    def __init__(self, outfile):
        self.json = gzip.open(outfile, 'wb')

    def spider_opened(self, spider):
        self.json.write('[')

        try:
            spider.set_pipeline(self)
        except:
            pass

    def process_item(self, item, spider):
        if 'url' in item:
            if item['url'] in self.urls:
                raise DropItem()
            else:
                self.urls.add(item['url'])

        if self.has_items:
            self.json.write(',\n')

        json.dump(item, self.json, cls=ScrapyJSONEncoder)
        self.has_items = True

        return item

    def spider_closed(self, spider):
        self.json.write(']')
        self.json.close()

class ParlSpider(CrawlSpider):
    name = "parlspider"
    geocode_url = 'http://api-adresse.data.gouv.fr/search/?q=%s'
    nd_photo_url = 'http://www.nosdeputes.fr/depute/photo/%s'
    ns_photo_url = 'http://www.nossenateurs.fr/senateur/photo/%s'

    allowed_domains = [
        "2007-2012.nosdeputes.fr",
        "2007-2012.nossenateurs.fr",
        "2012-2017.nosdeputes.fr",
        "2012-2017.nossenateurs.fr",
        "www.nosdeputes.fr",
        "www.nossenateurs.fr",
        "api-adresse.data.gouv.fr"
    ]

    start_urls = [
        "http://2007-2012.nosdeputes.fr/deputes/json",
        "http://2007-2012.nossenateurs.fr/senateurs/json",
        "http://2012-2017.nosdeputes.fr/deputes/json",
        "http://2012-2017.nossenateurs.fr/senateurs/json",
        "http://www.nosdeputes.fr/deputes/json",
        "http://www.nossenateurs.fr/senateurs/json"
    ]

    def parse(self, response):
        reps = json.loads(response.body_as_unicode())

        if 'deputes' in reps:
            reps = reps['deputes']
        elif 'senateurs' in reps:
            reps = reps['senateurs']

        for rep in reps:
            if 'depute' in rep:
                rep = rep['depute']
                yield Request(url=rep['url_nosdeputes_api'],
                              callback=self.parse_parlementaire)
            elif 'senateur' in rep:
                rep = rep['senateur']
                yield Request(url=rep['url_nossenateurs_api'],
                              callback=self.parse_parlementaire)

    def parse_parlementaire(self, response):
        rep = json.loads(response.body_as_unicode())
        if 'depute' in rep:
            rep = rep['depute']
            rep['chambre'] = 'AN'
            rep['photo_url'] = get_photo_url(rep['url_nosdeputes'],
                                             'depute')
        elif 'senateur' in rep:
            rep = rep['senateur']
            rep['chambre'] = 'SEN'
            rep['photo_url'] = get_photo_url(rep['url_nossenateurs'],
                                             'senateur')

        reqs = []

        for ad in rep['adresses']:
            adresse = ad['adresse']

            pattern = ur'Télé(phone|copie)\s*:\s*(\d[0-9 ]+\d)'
            for telm in re.finditer(pattern, adresse):
                if telm.group(1) == 'phone':
                    ad['tel'] = telm.group(2)
                else:
                    ad['fax'] = telm.group(2)

            lad = adresse.lower()
            if (not lad.startswith(u'assemblée nationale') and
                    not lad.startswith(u'sénat')):
                trimmed = re.sub(pattern, '', adresse)
                req = Request(url=self.get_geocode_url(trimmed),
                              callback=self.parse_geocode)

                req.meta['rep'] = rep
                req.meta['adresse'] = ad
                reqs.append(req)

        if len(reqs) > 0:
            req = reqs.pop()
            req.meta['requests'] = reqs
            yield req
        else:
            yield rep

    def get_geocode_url(self, q):
        return self.geocode_url % quote(q.encode('utf-8'))

    def parse_geocode(self, response):
        rep = response.meta['rep']
        adresse = response.meta['adresse']
        reqs = response.meta['requests']

        geo = json.loads(response.body_as_unicode())
        if 'features' in geo and len(geo['features']) > 0:
            adresse['geo'] = geo['features'][0]

        if len(reqs) > 0:
            req = reqs.pop()
            req.meta['requests'] = reqs
            yield req
        else:
            yield rep


commands = {
    'parl': { 'class': ParlSpider, 'output': 'parlementaires.json.gz' },
}
def crawl(spider, outfile, **spargs):
    tmpfile = ('%s.tmp' % outfile)

    if os.path.exists(tmpfile):
        os.remove(tmpfile)

    process = CrawlerProcess({
        'BOT_NAME': 'francedata',
        'LOG_LEVEL': 'INFO',
        'TELNETCONSOLE_ENABLED': False,
        'OUTPUT_FILE': tmpfile,
        'DUPEFILTER_CLASS': '__main__.URLScreenFilter',
        'ITEM_PIPELINES': {
            '__main__.FrancedataPipeline': 500
        },
    })

    process.crawl(spider, **spargs)
    process.start()

    if os.path.exists(outfile):
        os.remove(outfile)

    os.rename(tmpfile, outfile)

def update():
    if len(sys.argv) < 2:
        print 'Usage: %s command [outfile]'
        sys.exit(1)

    cmd = sys.argv[1]
    if len(sys.argv) > 2:
        outfile = sys.argv[2]
    else:
        outfile = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                           command['output'])

    if cmd not in commands:
        print 'Unknown command "%s"' % cmd
        sys.exit(1)

    command = commands[cmd]
    crawl(command['class'], outfile)

if __name__ == "__main__":
    update()