Repository navigation
Expand file tree
/
Copy pathWeb_Data_Extractor.txt
More file actions
1812 lines (1526 loc) · 61.9 KB
/
Copy pathWeb_Data_Extractor.txt
File metadata and controls
1812 lines (1526 loc) · 61.9 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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* =============================================================================
* Modular Web Data Extractor
* =============================================================================
*
* A flexible, extensible web scraping framework for browser DevTools.
* This script intelligently detects and extracts tabular and structured data
* from web pages using a plugin-based architecture where new data sources
* can be easily added.
*
* ARCHITECTURE OVERVIEW:
*
* 1. Core System
* - Registry for detectors and extractors
* - Main execution flow
* - Configuration management
*
* 2. Detector Modules
* - Detect specific data structures in the DOM
* - Return candidate elements for extraction
* - Include confidence scoring
*
* 3. Extractor Modules
* - Extract data from elements found by detectors
* - Transform raw DOM data into structured format
* - Handle special cases for different data structures
*
* 4. Utility Functions
* - DOM helpers
* - Text processing
* - Structure analysis
*
* =============================================================================
* HOW TO USE:
*
* 1. Copy this entire script
* 2. Open browser DevTools on any webpage (F12 or right-click > Inspect)
* 3. Paste into the Console tab and press Enter
* 4. The script will automatically detect and extract data
*
* =============================================================================
* HOW TO EXTEND:
*
* To add a new data source:
* 1. Add a new detector in the Detectors section
* 2. Add a corresponding extractor in the Extractors section
* 3. Register both in the initialization section
*
* See the existing modules for examples.
*
* =============================================================================
* Author: [Your Name]
* Version: 1.0.0
* =============================================================================
*/
// Immediately-invoked function expression (IIFE) to avoid polluting global scope
(function() {
'use strict';
/**
* =============================================================================
* CORE SYSTEM
* =============================================================================
* The core system manages the registry of detectors and extractors,
* handles execution flow, and provides configuration management.
*/
// Central registry for all detector and extractor modules
const WebDataExtractor = {
// Registries
detectors: [],
extractors: {},
// Configuration
config: {
debug: true, // Set to true for detailed console logs
maxDetectionAttempts: 5, // Maximum number of detector types to try
outputFormat: 'html', // 'html', 'json', or 'csv'
scrollForVirtualized: true, // Whether to scroll to reveal virtualized content
},
// Register a detector module
registerDetector: function(detector) {
if (!detector.name || typeof detector.detect !== 'function' || typeof detector.priority !== 'number') {
console.error('Invalid detector module:', detector);
return false;
}
this.detectors.push(detector);
// Sort detectors by priority (higher priority will run first)
this.detectors.sort((a, b) => b.priority - a.priority);
if (this.config.debug) {
console.log(`Registered detector: ${detector.name} (priority: ${detector.priority})`);
}
return true;
},
// Register an extractor module
registerExtractor: function(extractor) {
if (!extractor.name || !extractor.forDetector || typeof extractor.extract !== 'function') {
console.error('Invalid extractor module:', extractor);
return false;
}
this.extractors[extractor.forDetector] = extractor;
if (this.config.debug) {
console.log(`Registered extractor: ${extractor.name} for ${extractor.forDetector}`);
}
return true;
},
// Main execution function - made async to properly handle async extractors
run: async function() {
console.log('Web Data Extractor running...');
// Data will be collected here
const extractedData = [];
// Try each detector in order of priority
for (let i = 0; i < Math.min(this.detectors.length, this.config.maxDetectionAttempts); i++) {
const detector = this.detectors[i];
if (this.config.debug) {
console.log(`Trying detector: ${detector.name}`);
}
// Run the detector
const detectionResult = detector.detect();
// Skip if nothing detected
if (!detectionResult.elements || detectionResult.elements.length === 0) {
if (this.config.debug) {
console.log(`No elements found by ${detector.name}`);
}
continue;
}
console.log(`${detector.name} found ${detectionResult.elements.length} elements`);
// Get the corresponding extractor
const extractor = this.extractors[detector.name];
if (!extractor) {
console.error(`No extractor found for ${detector.name}`);
continue;
}
// Extract data
try {
// Key fix: Use await to ensure async extractors complete
const extractedItems = await Promise.resolve(extractor.extract(detectionResult));
if (extractedItems && extractedItems.length > 0) {
// Add extraction metadata
extractedItems.forEach(item => {
item.source = detector.name;
extractedData.push(item);
});
if (this.config.debug) {
console.log(`Extracted ${extractedItems.length} data items using ${extractor.name}`);
}
// Stop trying more detectors if we found data and detector says it's reliable
if (detectionResult.reliable !== false && extractedItems.length > 0) {
break;
}
}
} catch (error) {
console.error(`Error in ${extractor.name}:`, error);
}
}
// Display the results
if (extractedData.length > 0) {
console.log(`Extraction complete. Found ${extractedData.length} data tables.`);
this.displayResults(extractedData);
return extractedData;
} else {
console.log('No data could be extracted from this page.');
return [];
}
},
// Output the results
displayResults: function(data) {
if (this.config.outputFormat === 'json') {
console.log(JSON.stringify(data, null, 2));
return;
}
// Default to HTML display
const newWindow = window.open('', '_blank');
if (!newWindow) {
console.error('Unable to open result window. Check popup blocker settings.');
return;
}
const doc = newWindow.document;
// Generate HTML content
let content = '';
data.forEach((table, index) => {
content += `
<div class="table-container">
<h2>Table ${index + 1}: ${table.id || 'Extracted Data'}</h2>
<p class="meta">Source: ${table.source}</p>
<p class="meta">Selector: ${table.selector || 'N/A'}</p>
<table border="1">
<thead>
<tr>
${table.headers.map(header => `<th>${header}</th>`).join('')}
</tr>
</thead>
<tbody>
${table.rows.map(row => `
<tr>
${row.map(cell => `<td>${cell}</td>`).join('')}
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
});
// Write the HTML document
doc.write(`
<!DOCTYPE html>
<html>
<head>
<title>Extracted Web Data</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.table-container { margin-bottom: 40px; }
table { border-collapse: collapse; width: 100%; margin-top: 10px; }
th { background-color: #f2f2f2; padding: 8px; text-align: left; }
td { padding: 8px; border: 1px solid #ddd; }
tr:nth-child(even) { background-color: #f9f9f9; }
.meta { color: #666; font-size: 14px; margin: 5px 0; }
h1, h2 { color: #333; }
</style>
</head>
<body>
<h1>Extracted Web Data</h1>
${content}
</body>
</html>
`);
doc.close();
}
};
/**
* =============================================================================
* UTILITY FUNCTIONS
* =============================================================================
* These utility functions are used by multiple detectors and extractors.
* They handle common tasks like text processing, DOM analysis, etc.
*/
const Utilities = {
/**
* Cleans text by removing extra whitespace and trimming
* @param {string} text - Text to clean
* @returns {string} Cleaned text
*/
cleanText: function(text) {
if (!text) return '';
return text.replace(/\s+/g, ' ').trim();
},
/**
* Generates a CSS selector for uniquely identifying an element
* @param {HTMLElement} element - Element to generate selector for
* @returns {string} CSS selector
*/
generateSelector: function(element) {
if (!element || !element.tagName) return 'unknown';
// Try ID first (most specific)
if (element.id) {
return `#${element.id}`;
}
// Try classes
if (element.classList && element.classList.length > 0) {
const classes = Array.from(element.classList).join('.');
const selector = `.${classes}`;
const matchingElements = document.querySelectorAll(selector);
if (matchingElements.length === 1) {
return selector;
}
}
// Use tag name with classes
if (element.classList && element.classList.length > 0) {
const classes = Array.from(element.classList).join('.');
return `${element.tagName.toLowerCase()}.${classes}`;
}
// Use tag name and position
const siblings = element.parentNode ? element.parentNode.children : [];
let position = 0;
for (let i = 0; i < siblings.length; i++) {
if (siblings[i].tagName === element.tagName) {
position++;
}
if (siblings[i] === element) {
break;
}
}
// Return full path
const parentSelector = (element.parentNode === document)
? ''
: this.generateSelector(element.parentNode) + ' > ';
return `${parentSelector}${element.tagName.toLowerCase()}:nth-of-type(${position})`;
},
/**
* Gets a signature of an element's structure based on its children
* @param {HTMLElement} element - Element to analyze
* @returns {string} Structure signature
*/
getChildrenStructure: function(element) {
if (!element || !element.children) return '';
const childTags = Array.from(element.children).map(child => {
if (!child.classList) return child.tagName;
return `${child.tagName}${Array.from(child.classList).join('.')}`;
});
return childTags.join('|');
},
/**
* Checks if an element has matching structure to a signature
* @param {HTMLElement} element - Element to check
* @param {string} structureSignature - Signature to compare with
* @returns {boolean} True if structures match
*/
hasMatchingStructure: function(element, structureSignature) {
const elementSignature = this.getChildrenStructure(element);
return elementSignature === structureSignature;
},
/**
* Determines if text is likely to be a header based on content heuristics
* @param {string} text - Text to analyze
* @returns {boolean} True if likely a header
*/
isLikelyHeader: function(text) {
if (!text) return false;
// Headers are typically shorter
if (text.length > 50) return false;
// Headers often don't contain numbers (except for dates/years)
const hasNumbers = /\d+/.test(text);
const isDateOrYear = /^(19|20)\d{2}$/.test(text) || // Year
/^\d{1,2}\/\d{1,2}(\/\d{2,4})?$/.test(text); // Date
if (hasNumbers && !isDateOrYear) return false;
// Headers are often title case or uppercase
const isTitleCase = text !== text.toLowerCase() &&
(text === text.charAt(0).toUpperCase() + text.slice(1) ||
text.split(' ').every(word => word === word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()));
const isAllCaps = text === text.toUpperCase() && text.length > 1;
// Headers often have certain key terms
const hasHeaderTerms = /total|sum|average|name|date|time|description|title|category|type|id|number|count|price|cost|amount|quantity|value|rate|percent/i.test(text);
// Calculate a "headerness" score
let score = 0;
if (text.length < 20) score += 1;
if (isTitleCase) score += 1;
if (isAllCaps) score += 2;
if (hasHeaderTerms) score += 2;
if (!hasNumbers || isDateOrYear) score += 1;
return score >= 2;
},
/**
* Performs an action with a delay
* @param {number} ms - Milliseconds to delay
* @returns {Promise} Promise that resolves after the delay
*/
delay: function(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
};
/**
* =============================================================================
* DETECTORS
* =============================================================================
* Detector modules identify specific data structures in the DOM.
* Each detector returns candidate elements for extraction.
*/
/**
* HTML Table Detector
* Finds standard HTML <table> elements
*/
const HTMLTableDetector = {
name: 'HTMLTableDetector',
priority: 100, // Highest priority since HTML tables are most reliable
detect: function() {
const tables = document.querySelectorAll('table');
return {
elements: Array.from(tables),
reliable: tables.length > 0
};
}
};
/**
* AG Grid Detector
* Finds AG Grid components in the DOM with robust detection strategies
*/
const AGGridDetector = {
name: 'AGGridDetector',
priority: 90, // High priority
detect: function() {
const agGridElements = [];
// Strategy 1: Look for definitive AG Grid containers
const rootWrappers = document.querySelectorAll('.ag-root-wrapper');
if (rootWrappers.length > 0) {
rootWrappers.forEach(wrapper => {
// Verify it's an AG Grid by checking for child elements
if (wrapper.querySelector('.ag-root, [role="grid"], .ag-body-viewport, .ag-header')) {
agGridElements.push(wrapper);
}
});
}
// Strategy 2: Look for AG Grid roots directly
if (agGridElements.length === 0) {
const roots = document.querySelectorAll('.ag-root, [role="grid"].ag-root');
if (roots.length > 0) {
roots.forEach(root => {
// Get the wrapper if it exists, otherwise use the root
const wrapper = root.closest('.ag-root-wrapper') || root;
if (!agGridElements.includes(wrapper)) {
agGridElements.push(wrapper);
}
});
}
}
// Strategy 3: Look for elements with ag-theme classes (common in all implementations)
if (agGridElements.length === 0) {
const themedElements = document.querySelectorAll('[class*="ag-theme-"]');
themedElements.forEach(element => {
// Verify it's an AG Grid by checking for characteristic children
if (element.querySelector('.ag-root, .ag-header, .ag-body-viewport, [role="grid"], [role="row"][class*="ag-"]')) {
if (!agGridElements.includes(element)) {
agGridElements.push(element);
}
}
});
}
// Strategy 4: Look for AG Grid body viewport (common in all implementations)
if (agGridElements.length === 0) {
const viewports = document.querySelectorAll('.ag-body-viewport');
viewports.forEach(viewport => {
// Find the closest grid container
const container = viewport.closest('.ag-root-wrapper') ||
viewport.closest('.ag-root') ||
viewport.closest('[role="grid"]') ||
viewport.parentElement;
if (container && !agGridElements.includes(container)) {
agGridElements.push(container);
}
});
}
// Strategy 5: Look for header containers
if (agGridElements.length === 0) {
const headers = document.querySelectorAll('.ag-header');
headers.forEach(header => {
// Find the closest grid container
const container = header.closest('.ag-root-wrapper') ||
header.closest('.ag-root') ||
header.closest('[role="grid"]') ||
header.parentElement;
if (container && !agGridElements.includes(container)) {
agGridElements.push(container);
}
});
}
// Strategy 6: Check inside iframes
try {
const iframes = document.querySelectorAll('iframe');
iframes.forEach(iframe => {
try {
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
if (iframeDoc) {
// Look for AG Grid in iframe using the main indicators
const iframeGrids = iframeDoc.querySelectorAll('.ag-root-wrapper, .ag-root, [role="grid"].ag-root, .ag-body-viewport, .ag-header');
if (iframeGrids.length > 0) {
// Found AG Grid in iframe, add the iframe itself
agGridElements.push(iframe);
}
}
} catch (e) {
// Silent fail for cross-origin iframes
}
});
} catch (e) {
console.log('Error checking iframes:', e);
}
return {
elements: agGridElements,
reliable: agGridElements.length > 0
};
}
};
/**
* Div Table Detector
* Finds div structures that mimic tables (using CSS Grid or Flexbox)
*/
const DivTableDetector = {
name: 'DivTableDetector',
priority: 80, // Medium-high priority
detect: function() {
const candidates = [];
// Find potential container elements
const containers = document.querySelectorAll('div, section, article');
for (const container of containers) {
// Skip if too small or empty
if (container.children.length < 2) continue;
// Check for grid/flex layout
const style = window.getComputedStyle(container);
const isGrid = style.display === 'grid';
const isFlex = style.display === 'flex';
if (isGrid || isFlex) {
// Check for repeated structure in children
const childStructure = Utilities.getChildrenStructure(container.children[0]);
let consistentStructure = true;
// Check if at least 3 children have similar structure
if (container.children.length >= 3) {
for (let i = 1; i < Math.min(container.children.length, 5); i++) {
if (!Utilities.hasMatchingStructure(container.children[i], childStructure)) {
consistentStructure = false;
break;
}
}
if (consistentStructure) {
candidates.push(container);
}
}
}
}
return {
elements: candidates,
reliable: candidates.length > 0
};
}
};
/**
* List Detector
* Finds list structures (ul/ol) that might contain tabular data
*/
const ListDetector = {
name: 'ListDetector',
priority: 70, // Medium priority
detect: function() {
const lists = Array.from(document.querySelectorAll('ul, ol')).filter(list => {
const items = list.querySelectorAll('li');
// Need at least 3 items for a meaningful data structure
if (items.length < 3) return false;
// Check if list items have consistent structure
const firstItemStructure = Utilities.getChildrenStructure(items[0]);
for (let i = 1; i < Math.min(items.length, 5); i++) {
if (!Utilities.hasMatchingStructure(items[i], firstItemStructure)) {
return false;
}
}
return true;
});
return {
elements: lists,
reliable: lists.length > 0
};
}
};
/**
* Link Detector
* Fallback detector that finds links as a simple data source
*/
const LinkDetector = {
name: 'LinkDetector',
priority: 10, // Lowest priority - fallback option
detect: function() {
const links = document.querySelectorAll('a');
// Only return links if we have enough to be meaningful
return {
elements: links.length >= 5 ? [document.body] : [],
reliable: false // Links are never considered a reliable data source
};
}
};
/**
* =============================================================================
* EXTRACTORS
* =============================================================================
* Extractor modules pull structured data from elements found by detectors.
* Each extractor corresponds to a specific detector.
*/
/**
* HTML Table Extractor
* Extracts data from standard HTML <table> elements
*/
const HTMLTableExtractor = {
name: 'HTMLTableExtractor',
forDetector: 'HTMLTableDetector',
extract: function(detectionResult) {
const extractedTables = [];
detectionResult.elements.forEach((table, tableIndex) => {
const tableData = {
id: `table-${tableIndex}`,
selector: Utilities.generateSelector(table),
headers: [],
rows: []
};
// Detect headers using comprehensive detection approach
this.detectTableHeaders(table, tableData);
// Extract rows
this.extractTableRows(table, tableData);
extractedTables.push(tableData);
});
return extractedTables;
},
/**
* Comprehensive header detection for HTML tables
* @param {HTMLElement} table - Table element
* @param {Object} tableData - Table data object to populate
*/
detectTableHeaders: function(table, tableData) {
const headerCandidates = [];
// Method 1: Check for semantic thead and th elements (highest confidence)
const theadElement = table.querySelector('thead');
if (theadElement) {
const headerRows = theadElement.querySelectorAll('tr');
if (headerRows.length > 0) {
// Use first row in thead
const headerCells = headerRows[0].querySelectorAll('th, td');
headerCells.forEach((cell, index) => {
const text = Utilities.cleanText(cell.textContent);
headerCandidates[index] = {
text: text,
confidence: 10, // High confidence for thead elements
source: 'thead'
};
});
}
} else {
// Method 2: Look for th elements in the first row
const firstRow = table.querySelector('tr');
if (firstRow) {
const thCells = firstRow.querySelectorAll('th');
if (thCells.length > 0) {
thCells.forEach((cell, index) => {
const text = Utilities.cleanText(cell.textContent);
headerCandidates[index] = {
text: text,
confidence: 8, // Good confidence for th elements
source: 'th'
};
});
} else {
// Method 3: Use first row cells with styling analysis
const firstRowCells = firstRow.querySelectorAll('td');
firstRowCells.forEach((cell, index) => {
const text = Utilities.cleanText(cell.textContent);
// Calculate confidence based on styling and content
let confidence = 5; // Base confidence for first row
// Check styling indicators
const style = window.getComputedStyle(cell);
if (style.fontWeight === 'bold' || parseInt(style.fontWeight) >= 600) confidence += 1;
if (style.backgroundColor !== 'rgba(0, 0, 0, 0)' && style.backgroundColor !== 'transparent') confidence += 1;
if (style.textAlign === 'center') confidence += 0.5;
// Check content indicators
if (Utilities.isLikelyHeader(text)) confidence += 1.5;
headerCandidates[index] = {
text: text,
confidence: confidence,
source: 'firstRow'
};
});
}
}
}
// Method 4: Check for ARIA roles
const ariaHeaders = table.querySelectorAll('[role="columnheader"], [role="rowheader"]');
if (ariaHeaders.length > 0) {
ariaHeaders.forEach(header => {
// Try to determine the column index
const headerRow = header.closest('tr');
if (headerRow) {
const cells = headerRow.querySelectorAll('td, th');
for (let i = 0; i < cells.length; i++) {
if (cells[i] === header) {
const text = Utilities.cleanText(header.textContent);
// Only override if confidence is higher
const existingConfidence = headerCandidates[i] ? headerCandidates[i].confidence : 0;
if (existingConfidence < 9) {
headerCandidates[i] = {
text: text,
confidence: 9, // High confidence for ARIA roles
source: 'aria'
};
}
break;
}
}
}
});
}
// Find the maximum number of cells in any row
const rows = table.querySelectorAll('tr');
let maxCells = 0;
rows.forEach(row => {
const cellCount = row.querySelectorAll('td, th').length;
if (cellCount > maxCells) maxCells = cellCount;
});
// Create final header array from candidates
for (let i = 0; i < maxCells; i++) {
if (headerCandidates[i] && headerCandidates[i].text) {
tableData.headers.push(headerCandidates[i].text);
} else {
// Generate generic header name
tableData.headers.push(`Column ${i+1}`);
}
}
},
/**
* Extract rows from HTML table
* @param {HTMLElement} table - Table element
* @param {Object} tableData - Table data object to populate
*/
extractTableRows: function(table, tableData) {
// Determine where to start extracting rows
let startIndex = 0;
// Skip header row if it's in the table body (not in thead)
const hasHeaderRowInBody = !table.querySelector('thead') &&
(table.querySelector('tr th') ||
table.querySelector('tr [role="columnheader"]'));
if (hasHeaderRowInBody) {
startIndex = 1;
}
// Get all rows
const rows = table.querySelectorAll('tbody tr, tr');
// Extract data from each row
for (let i = startIndex; i < rows.length; i++) {
const row = rows[i];
// Skip header rows
if (row.parentElement && row.parentElement.tagName === 'THEAD') continue;
const rowData = [];
const cells = row.querySelectorAll('td, th');
cells.forEach(cell => {
rowData.push(Utilities.cleanText(cell.textContent));
});
// Only add non-empty rows
if (rowData.length > 0 && rowData.some(cell => cell)) {
tableData.rows.push(rowData);
}
}
}
};
/**
* AG Grid Extractor
* Extracts data from AG Grid components, handling virtualized content with multi-pass approach
*/
const AGGridExtractor = {
name: 'AGGridExtractor',
forDetector: 'AGGridDetector',
extract: async function(detectionResult) {
const extractedTables = [];
// Process each detected AG Grid
for (let gridIndex = 0; gridIndex < detectionResult.elements.length; gridIndex++) {
const gridElement = detectionResult.elements[gridIndex];
const tableData = {
id: `ag-grid-${gridIndex}`,
selector: Utilities.generateSelector(gridElement),
headers: [],
rows: []
};
// Step 1: Extract headers
this.extractHeaders(gridElement, tableData);
// Step 2: Extract visible rows first
this.extractVisibleRows(gridElement, tableData);
// Step 3: If scrolling is enabled, try to reveal more rows with multi-pass approach
if (WebDataExtractor.config.scrollForVirtualized) {
await this.multiPassExtraction(gridElement, tableData);
}
// Only add grids that have both headers and rows
if (tableData.headers.length > 0 && tableData.rows.length > 0) {
extractedTables.push(tableData);
}
}
return extractedTables;
},
/**
* Extract headers from AG Grid
* @param {HTMLElement} gridElement - AG Grid element
* @param {Object} tableData - Table data object to populate
*/
extractHeaders: function(gridElement, tableData) {
// Strategy 1: Look for header cells with role="columnheader"
const headerCells = gridElement.querySelectorAll('[role="columnheader"], .ag-header-cell');
// First, collect all header information with positions
const headerInfo = [];
if (headerCells.length > 0) {
headerCells.forEach((cell, index) => {
// Try to get the left position to understand visual order
const style = window.getComputedStyle(cell);
const leftPos = parseInt(style.left) || parseInt(style.getPropertyValue('left')) || 0;
// Try various ways to get header text
const headerLabel = cell.querySelector('.ag-header-cell-text, .ag-header-cell-label');
const cellValue = cell.querySelector('.ag-cell-value');
let headerText = '';
if (headerLabel) {
headerText = Utilities.cleanText(headerLabel.textContent);
} else if (cellValue) {
headerText = Utilities.cleanText(cellValue.textContent);
} else {
// Text extraction that filters out menu buttons and icons
const walker = document.createTreeWalker(
cell,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
if (node.parentElement &&
(node.parentElement.classList.contains('ag-header-cell-menu-button') ||
node.parentElement.classList.contains('ag-header-icon'))) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
},
false
);
let cellTextContent = '';
while (walker.nextNode()) {
cellTextContent += walker.currentNode.textContent;
}
headerText = Utilities.cleanText(cellTextContent);
}
if (headerText) {
// Store visual position information along with header text
headerInfo.push({
text: headerText,
domIndex: index,
visualPos: leftPos,
colId: cell.getAttribute('col-id') || `col-${index}`
});
}
});
// Sort headers by visual position (left CSS value) to match what the user sees
headerInfo.sort((a, b) => a.visualPos - b.visualPos);
// Store column mappings for data extraction
tableData.columnMappings = headerInfo.map(info => info.colId);
// Set the headers in the tableData
tableData.headers = headerInfo.map(info => info.text);
// Store visual to DOM index mapping for use in data extraction
tableData.visualToDomIndex = {};
headerInfo.forEach((info, visualIndex) => {
tableData.visualToDomIndex[visualIndex] = info.domIndex;
});
}
// Strategy 2: Look for header container if no headers found yet
if (tableData.headers.length === 0) {
// Try to find any elements in the header that might contain header text
const headerContainers = gridElement.querySelectorAll(
'.ag-header, .ag-header-container, .ag-header-row, .ag-header-row-column'
);
if (headerContainers.length > 0) {
// Process each container to find potential header texts
headerContainers.forEach(container => {
// Look for specific header text elements first
const textElements = container.querySelectorAll(
'.ag-header-cell-text, span:not(.ag-icon), div:not(.ag-header-cell-menu-button)'
);
if (textElements.length > 0) {
const texts = [];
textElements.forEach((el, index) => {
// Try to get visual position
const style = window.getComputedStyle(el);
const leftPos = parseInt(style.left) || parseInt(style.getPropertyValue('left')) || index * 100; // Fallback to index-based position
// Only include direct text, not from child elements with their own headers
if (el.children.length === 0 || !el.querySelector('.ag-header-cell-text')) {
const text = Utilities.cleanText(el.textContent);
if (text && text.length < 50) {
texts.push({
text: text,
visualPos: leftPos,
domIndex: index,
colId: `col-${index}`
});
}
}
});