-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextract_data.py
More file actions
executable file
·395 lines (336 loc) · 17 KB
/
extract_data.py
File metadata and controls
executable file
·395 lines (336 loc) · 17 KB
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
#!/usr/bin/env python3
"""
Extract complete data from Karnataka Land Records website
This script will:
1. Go through all districts
2. For each district, get all taluks
3. For each taluk, get all hoblis
4. For each hobli, get all villages from the table
"""
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import json
import time
from datetime import datetime
try:
from webdriver_manager.chrome import ChromeDriverManager
USE_WEBDRIVER_MANAGER = True
except ImportError:
USE_WEBDRIVER_MANAGER = False
print("Note: webdriver-manager not installed. Make sure ChromeDriver is in PATH.")
def setup_driver():
"""Setup Chrome driver"""
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-blink-features=AutomationControlled')
# Run headless (no browser window) - faster and cleaner
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--window-size=1920,1080')
if USE_WEBDRIVER_MANAGER:
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
else:
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(2) # Ultra-fast implicit wait
return driver
def get_villages_from_table(driver):
"""Extract village names from the table, handling pagination"""
all_villages = []
try:
# First, check if there's pagination and get total pages
pagination_info = driver.execute_script("""
var totalPages = 1;
// Method 1: Look for "Page X of Y" text
var allText = document.body.textContent || document.body.innerText;
var pageMatch = allText.match(/Page\s+(\d+)\s+of\s+(\d+)/i);
if (pageMatch) {
totalPages = parseInt(pageMatch[2]);
return {totalPages: totalPages, method: 'text'};
}
// Method 2: Look for pagination links with page numbers
var pageLinks = document.querySelectorAll('a[href*="Page"], a[onclick*="Page"], a[href*="__doPostBack"]');
var pageNumbers = new Set();
for (var i = 0; i < pageLinks.length; i++) {
var link = pageLinks[i];
var text = link.textContent.trim();
var num = parseInt(text);
if (!isNaN(num) && num > 0) {
pageNumbers.add(num);
}
// Also check href/onclick for page numbers
var href = link.getAttribute('href') || link.getAttribute('onclick') || '';
var hrefMatch = href.match(/Page[\\$]?(\\d+)/i);
if (hrefMatch) {
pageNumbers.add(parseInt(hrefMatch[1]));
}
}
if (pageNumbers.size > 0) {
totalPages = Math.max.apply(null, Array.from(pageNumbers));
return {totalPages: totalPages, method: 'links'};
}
// Method 3: Look for GridView pagination (ASP.NET)
var gridView = document.querySelector('[id*="grd"], [id*="Grid"], table[id*="gv"]');
if (gridView) {
var paginationRow = gridView.querySelector('tr:last-child, tfoot tr');
if (paginationRow) {
var paginationText = paginationRow.textContent || paginationRow.innerText;
var match = paginationText.match(/(\\d+)\\s*of\\s*(\\d+)/i);
if (match) {
totalPages = parseInt(match[2]);
return {totalPages: totalPages, method: 'gridview'};
}
}
}
return {totalPages: totalPages, method: 'default'};
""")
total_pages = pagination_info.get('totalPages', 1) if pagination_info else 1
if total_pages > 1:
print(f" Found {total_pages} pages of villages")
# Extract villages from all pages
for page_num in range(1, total_pages + 1):
if page_num > 1:
# Navigate to specific page using multiple methods
page_clicked = driver.execute_script(f"""
var clicked = false;
var targetPage = {page_num};
// Method 1: Find link with exact page number text
var allLinks = document.querySelectorAll('a');
for (var i = 0; i < allLinks.length; i++) {{
var link = allLinks[i];
var text = link.textContent.trim();
if (text === targetPage.toString() || text === 'Page ' + targetPage) {{
link.click();
clicked = true;
break;
}}
}}
// Method 2: Find __doPostBack link with Page$X
if (!clicked) {{
var postBackLinks = document.querySelectorAll('a[href*="__doPostBack"]');
for (var j = 0; j < postBackLinks.length; j++) {{
var href = postBackLinks[j].getAttribute('href') || '';
if (href.indexOf('Page$' + targetPage) !== -1 ||
href.indexOf('Page\\\\$' + targetPage) !== -1 ||
href.indexOf('Page' + targetPage) !== -1) {{
postBackLinks[j].click();
clicked = true;
break;
}}
}}
}}
// Method 3: Use "Next" button if on previous page
if (!clicked && targetPage > 1) {{
var nextLinks = document.querySelectorAll('a');
for (var k = 0; k < nextLinks.length; k++) {{
var text = nextLinks[k].textContent.trim().toLowerCase();
if (text === 'next' || text === '>' || text.indexOf('next') !== -1) {{
nextLinks[k].click();
clicked = true;
break;
}}
}}
}}
return clicked;
""")
if page_clicked:
time.sleep(0.5) # Ultra-fast wait for page load
else:
print(f" Warning: Could not navigate to page {page_num}")
# Try to continue anyway - might be on correct page
# Extract villages from current page
villages_js = driver.execute_script("""
var villages = [];
var tables = document.getElementsByTagName('table');
for (var i = 0; i < tables.length; i++) {
var table = tables[i];
var rows = table.getElementsByTagName('tr');
if (rows.length > 1) {
// Find village column index from header
var headerRow = rows[0];
var headers = [];
var headerCells = headerRow.getElementsByTagName('th');
if (headerCells.length === 0) {
headerCells = headerRow.getElementsByTagName('td');
}
for (var h = 0; h < headerCells.length; h++) {
headers.push(headerCells[h].textContent.trim().toLowerCase());
}
var villageColIdx = -1;
for (var idx = 0; idx < headers.length; idx++) {
if (headers[idx].indexOf('village') !== -1 || headers[idx].indexOf('vlg') !== -1) {
villageColIdx = idx;
break;
}
}
if (villageColIdx === -1 && headers.length >= 4) {
villageColIdx = 3; // Default to 4th column
}
// Extract villages from data rows (skip header)
for (var r = 1; r < rows.length; r++) {
var cells = rows[r].getElementsByTagName('td');
// Skip pagination rows (usually have fewer cells or contain "Page")
var rowText = rows[r].textContent || rows[r].innerText;
if (rowText.indexOf('Page') !== -1) continue;
if (villageColIdx >= 0 && cells.length > villageColIdx) {
var village = cells[villageColIdx].textContent.trim();
if (village && villages.indexOf(village) === -1) {
villages.push(village);
}
} else if (cells.length >= 4) {
var village = cells[3].textContent.trim();
if (village && villages.indexOf(village) === -1) {
villages.push(village);
}
}
}
if (villages.length > 0) break;
}
}
return villages;
""")
page_villages = villages_js if villages_js else []
all_villages.extend(page_villages)
if page_num > 1:
print(f" Page {page_num}: Found {len(page_villages)} villages")
# Remove duplicates
unique_villages = list(dict.fromkeys(all_villages)) # Preserves order
except Exception as e:
print(f" Warning: Could not extract villages: {e}")
import traceback
traceback.print_exc()
return unique_villages
def extract_all_data():
"""Main extraction function"""
driver = setup_driver()
try:
print("Loading website...")
driver.get("https://landrecords.karnataka.gov.in/service3/")
time.sleep(0.5) # Ultra-fast initial load
# Get all districts using fast JavaScript
districts = driver.execute_script("""
var select = document.querySelector('select[name="ddl_district"]');
var options = [];
for (var i = 0; i < select.options.length; i++) {
var opt = select.options[i];
var val = opt.value;
if (val !== '0' && val !== 'All') {
options.push({value: val, label: opt.text.trim()});
}
}
return options;
""")
print(f"Found {len(districts)} districts\n")
start_time = datetime.now()
all_data = []
for i, district in enumerate(districts, 1):
elapsed = (datetime.now() - start_time).total_seconds()
print(f"[{i}/{len(districts)}] Processing district: {district['label']} ({district['value']}) - ⏱️ {elapsed:.1f}s")
# Select district using fast JavaScript
driver.execute_script(f"""
var select = document.querySelector('select[name="ddl_district"]');
select.value = '{district['value']}';
select.dispatchEvent(new Event('change', {{ bubbles: true }}));
""")
time.sleep(0.5) # Ultra-fast wait time
# Get all taluks using JavaScript (faster)
taluks = driver.execute_script("""
var select = document.querySelector('select[name="ddl_taluk"]');
var options = [];
for (var i = 0; i < select.options.length; i++) {
var opt = select.options[i];
var val = opt.value;
if (val !== '0' && val !== 'All' && val !== '--Select--') {
options.push({value: val, label: opt.text.trim()});
}
}
return options;
""")
print(f" Found {len(taluks)} taluks")
district_data = {
"value": district['value'],
"label": district['label'],
"taluks": []
}
for j, taluk in enumerate(taluks, 1):
print(f" [{j}/{len(taluks)}] Processing taluk: {taluk['label']}")
# Select taluk using fast JavaScript
driver.execute_script(f"""
var select = document.querySelector('select[name="ddl_taluk"]');
select.value = '{taluk['value']}';
select.dispatchEvent(new Event('change', {{ bubbles: true }}));
""")
time.sleep(0.5) # Ultra-fast wait time
# Get all hoblis using JavaScript (faster)
hoblis = driver.execute_script("""
var select = document.querySelector('select[name="ddl_hobli"]');
var options = [];
for (var i = 0; i < select.options.length; i++) {
var opt = select.options[i];
var val = opt.value;
if (val !== '0' && val !== 'All' && val !== '--Select--') {
options.push({value: val, label: opt.text.trim()});
}
}
return options;
""")
print(f" Found {len(hoblis)} hoblis")
taluk_data = {
"value": taluk['value'],
"label": taluk['label'],
"hoblis": []
}
for k, hobli in enumerate(hoblis, 1):
print(f" [{k}/{len(hoblis)}] Processing hobli: {hobli['label']}")
# Select hobli using fast JavaScript
driver.execute_script(f"""
var select = document.querySelector('select[name="ddl_hobli"]');
select.value = '{hobli['value']}';
select.dispatchEvent(new Event('change', {{ bubbles: true }}));
""")
time.sleep(0.5) # Ultra-fast wait time - table loads quickly
# Get villages from table (handles pagination automatically)
villages = get_villages_from_table(driver)
if len(villages) > 0:
print(f" Found {len(villages)} total villages (across all pages)")
taluk_data["hoblis"].append({
"value": hobli['value'],
"label": hobli['label'],
"villages": [{"value": str(idx+1), "label": v} for idx, v in enumerate(villages)]
})
time.sleep(0.1) # Ultra-minimal delay
district_data["taluks"].append(taluk_data)
print(f" Completed taluk: {taluk['label']}\n")
all_data.append(district_data)
print(f" Completed district: {district['label']}\n")
time.sleep(0.2) # Ultra-minimal delay between districts
return all_data
finally:
driver.quit()
if __name__ == "__main__":
print("=" * 60)
print("Karnataka Land Records Data Extraction")
print("=" * 60)
print()
try:
data = extract_all_data()
# Save to JSON file
output_file = "complete-karnataka-data.json"
with open(output_file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print("\n" + "=" * 60)
print("Extraction Complete!")
print("=" * 60)
print(f"Total districts: {len(data)}")
total_taluks = sum(len(d["taluks"]) for d in data)
total_hoblis = sum(len(t["hoblis"]) for d in data for t in d["taluks"])
total_villages = sum(len(h["villages"]) for d in data for t in d["taluks"] for h in t["hoblis"])
print(f"Total taluks: {total_taluks}")
print(f"Total hoblis: {total_hoblis}")
print(f"Total villages: {total_villages}")
print(f"\nData saved to: {output_file}")
except Exception as e:
print(f"\nError: {e}")
import traceback
traceback.print_exc()