-
Notifications
You must be signed in to change notification settings - Fork 15
/
haryana.py
266 lines (211 loc) · 8.5 KB
/
haryana.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
import requests
from requests.adapters import HTTPAdapter
from scrapy import Selector
import csv
import PyPDF2
import os.path
import os
#--------------------define variables-------------------
PDF_FOLDER = 'haryana_pdfs/'
OUTPUT_FILE = 'haryana.csv'
CSV_FLAG = True
#-------------------------------------------------------
#--------------------define global functions------------
def makeCookieString(cookie_dic):
return "; ".join([str(key) + "=" + str(cookie_dic[key]) for key in cookie_dic]) + ';'
# -----------------------------------------------------------------------------------------------------------------------
class HaryanaScraper:
def __init__(self,
base_url='http://ceoharyana.nic.in/?module=draftroll',
checkdraft_url='http://ceoharyana.nic.in/directs/check_draft.php'
):
# define session object
self.session = requests.Session()
self.session.mount('https://', HTTPAdapter(max_retries=4))
# set proxy
# self.session.proxies.update({'http': 'http://127.0.0.1:40328'})
# define urls
self.base_url = base_url
self.checkdraft_url = checkdraft_url
def GetDistrictList(self):
# set url
url = self.base_url
# get request
ret = self.session.get(url)
if ret.status_code == 200:
values = Selector(text=ret.text).xpath('//select[@id="district"]/option/@value').extract()
names = Selector(text=ret.text).xpath('//select[@id="district"]/option/text()').extract()
districts = []
for idx in range(0, len(values)):
if values[idx] != '0':
district = {
'value': values[idx],
'name': names[idx]
}
districts.append(district)
print(districts)
return districts
else:
print('failed to get district list')
return None
def GetConstituencyList(self, district_id):
# set post data
params = {}
params['Type'] = 'dist'
params['ID'] = district_id
# set url
url = self.checkdraft_url
# get request
ret = self.session.get(url, params=params)
if ret.status_code == 200:
values = Selector(text=ret.text).xpath('//select[@id="ac"]/option/@value').extract()
names = Selector(text=ret.text).xpath('//select[@id="ac"]/option/text()').extract()
constituencies = []
for idx in range(0, len(values)):
if values[idx] != '0':
constituency = {
'value': values[idx],
'name': names[idx]
}
constituencies.append(constituency)
print(constituencies)
return constituencies
else:
print('failed to get constituency list')
return None
def GetPollingStationList(self, constituency_id):
# set post data
params = {}
params['Type'] = 'ac'
params['ID'] = constituency_id
# set url
url = self.checkdraft_url
# get request
ret = self.session.get(url, params=params)
if ret.status_code == 200:
values = Selector(text=ret.text).xpath('//select[@id="ps"]/option/@value').extract()
names = Selector(text=ret.text).xpath('//select[@id="ps"]/option/text()').extract()
stations = []
for idx in range(0, len(values)):
if values[idx] != '0':
station = {
'value': values[idx],
'name': names[idx]
}
stations.append(station)
print(stations)
return stations
else:
print('failed to get polling station list')
return None
def GetPdfInfo(self, station_id):
# set post data
params = {}
params['Type'] = 'pdf'
params['ID'] = station_id
# set url
url = self.checkdraft_url
# get request
ret = self.session.get(url, params=params)
if ret.status_code == 200:
download_url = Selector(text=ret.text).xpath('//a/@href').extract()[0]
file_name = Selector(text=ret.text).xpath('//a/text()').extract()[0]
pdf_info = {
'download_url': download_url,
'file_name': file_name.split('/')[1]
}
print(pdf_info)
return pdf_info
else:
print('failed to get pdf information')
return None
def DownloadPdfFile(self, download_url, filename):
# set url
url = download_url
# get request
ret = self.session.get(url, stream=True)
if ret.status_code == 200:
with open(PDF_FOLDER + filename, 'wb') as f:
f.write(ret.content)
print('success to download %s' % (filename))
else:
print('failed to get pdf information')
def WriteHeader(self):
# set headers
header_info = []
header_info.append('district_name')
header_info.append('assembly_constituency')
header_info.append('polling_station_name')
header_info.append('filename')
# write header into output csv file
writer = csv.writer(open(OUTPUT_FILE, 'w'), delimiter=',', lineterminator='\n')
writer.writerow(header_info)
def WriteData(self, data):
# write data into output csv file
writer = csv.writer(open(OUTPUT_FILE, 'a'), delimiter=',', lineterminator='\n')
writer.writerow(data)
def CheckPdfFile(self, file_name):
if os.path.isfile(PDF_FOLDER + file_name) == True:
if os.stat(PDF_FOLDER + file_name).st_size == 0:
os.unlink(PDF_FOLDER + file_name)
return False
try:
print(PDF_FOLDER + file_name);
PyPDF2.PdfFileReader(open(PDF_FOLDER + file_name, "rb"))
except PyPDF2.utils.PdfReadError:
os.unlink(PDF_FOLDER + file_name)
return False
else:
return True
else:
return False
def Start(self):
# write header into output csv file
if CSV_FLAG == True: self.WriteHeader()
# get district list
print('getting districts ...')
districts = self.GetDistrictList()
for district in districts:
district_id = district['value']
district_name = district['name']
# get constituency list
print('getting constituencies of %s ...' % (district_name))
constituencies = self.GetConstituencyList(district_id)
for constituency in constituencies:
constituency_id = constituency['value']
constituency_name = constituency['name']
# get station list
print('getting polling stations of %s ...' % (constituency_name))
stations = self.GetPollingStationList(constituency_id)
for station in stations:
station_id = station['value']
station_name = station['name']
# get pdf information
print('getting pdf information of %s ...' % (station_name))
pdf_info = self.GetPdfInfo(station_id)
download_url = pdf_info['download_url']
filename = pdf_info['file_name']
# download and save pdf file
if self.CheckPdfFile(filename) == False:
print('downloading %s ...' % (filename))
self.DownloadPdfFile(download_url, filename)
if CSV_FLAG == True:
# write data into output csv file
data =[]
data.append(district_name)
data.append(constituency_name)
data.append(station_name)
data.append(filename)
self.WriteData(data)
# break
#
# break
# break
#------------------------------------------------------- main -------------------------------------------------------
def main():
# create scraper object
scraper = HaryanaScraper()
# start to scrape
scraper.Start()
if __name__ == '__main__':
main()