-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisual_recorder_backend.py
More file actions
361 lines (282 loc) · 12.1 KB
/
visual_recorder_backend.py
File metadata and controls
361 lines (282 loc) · 12.1 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
"""
Visual Scraper Recorder - Backend Integration
Processes recorded actions and generates scraper configurations
"""
import json
from typing import List, Dict, Any, Optional
from dataclasses import dataclass, asdict
from collections import Counter
import re
from pathlib import Path
@dataclass
class RecordedAction:
"""Represents a single recorded user action"""
type: str # 'click', 'extract', 'navigate', 'wait', 'container'
selector: str
timestamp: int
field: Optional[str] = None
data: Optional[str] = None
tag_name: Optional[str] = None
attributes: Optional[Dict] = None
class RecordingAnalyzer:
"""Analyzes recorded actions to generate optimal scraper configuration"""
def __init__(self, actions: List[Dict]):
self.actions = [RecordedAction(**action) for action in actions]
self.extracted_fields = {}
self.container_selector = None
self.pagination_selector = None
def analyze(self) -> Dict[str, Any]:
"""Analyze recorded actions and generate configuration"""
# 1. Identify container (common parent of extracted elements)
self.container_selector = self._detect_container()
# 2. Extract field mappings
self.extracted_fields = self._extract_fields()
# 3. Detect pagination
self.pagination_selector = self._detect_pagination()
# 4. Optimize selectors for stability
self.extracted_fields = self._optimize_selectors(self.extracted_fields)
# 5. Generate final configuration
config = self._generate_config()
return config
def _detect_container(self) -> str:
"""Detect the container selector by finding common parent"""
extract_actions = [a for a in self.actions if a.type == 'extract']
if not extract_actions:
return 'body'
# Check if user explicitly set container
container_actions = [a for a in self.actions if a.type == 'container']
if container_actions:
return container_actions[-1].selector # Use most recent
# Analyze selectors to find common parent
selectors = [a.selector for a in extract_actions]
# Find common ancestor by analyzing selector patterns
common_parts = self._find_common_selector_pattern(selectors)
if common_parts:
return common_parts
# Fallback: use first two levels of first selector
first_selector = selectors[0]
parts = first_selector.split(' ')
if len(parts) >= 2:
return ' '.join(parts[:2])
return first_selector.split(' ')[0] if ' ' in first_selector else 'body'
def _find_common_selector_pattern(self, selectors: List[str]) -> Optional[str]:
"""Find common pattern in selectors"""
if not selectors:
return None
# Split selectors into parts
selector_parts = [s.split(' ') for s in selectors]
# Find common prefix
common_prefix = []
for parts in zip(*selector_parts):
if len(set(parts)) == 1: # All same
common_prefix.append(parts[0])
else:
break
if len(common_prefix) >= 1:
return ' '.join(common_prefix)
# Look for common class patterns
class_pattern = re.compile(r'\.([\w-]+)')
common_classes = []
for selector in selectors:
classes = class_pattern.findall(selector)
common_classes.extend(classes)
# Find most common class
if common_classes:
most_common = Counter(common_classes).most_common(1)[0][0]
return f'.{most_common}'
return None
def _extract_fields(self) -> Dict[str, str]:
"""Extract field name to selector mappings"""
fields = {}
for action in self.actions:
if action.type == 'extract' and action.field:
# If multiple extractions for same field, use most recent
fields[action.field] = action.selector
return fields
def _detect_pagination(self) -> Optional[str]:
"""Detect pagination by looking for navigation clicks"""
click_actions = [a for a in self.actions if a.type == 'click']
# Look for common pagination patterns
pagination_patterns = [
'next', 'pagination', 'page', 'more',
'load-more', 'show-more', 'forward'
]
for action in click_actions:
selector_lower = action.selector.lower()
for pattern in pagination_patterns:
if pattern in selector_lower:
return action.selector
return None
def _optimize_selectors(self, fields: Dict[str, str]) -> Dict[str, str]:
"""Optimize selectors for stability and reliability"""
optimized = {}
for field_name, selector in fields.items():
# Remove absolute positioning (nth-child with numbers)
optimized_selector = re.sub(r':nth-child\(\d+\)', '', selector)
# Simplify if possible
optimized_selector = self._simplify_selector(optimized_selector)
optimized[field_name] = optimized_selector
return optimized
def _simplify_selector(self, selector: str) -> str:
"""Simplify selector while maintaining specificity"""
parts = selector.split(' ')
# If selector is too long, keep first and last 2 parts
if len(parts) > 4:
simplified = parts[:2] + parts[-2:]
return ' '.join(simplified)
return selector
def _generate_config(self) -> Dict[str, Any]:
"""Generate final scraper configuration"""
# Get target URL from first navigation action
target_url = None
for action in self.actions:
if action.type == 'navigate':
target_url = action.selector # URL stored in selector field
break
config = {
'name': 'Recorded Scraper',
'description': f'Auto-generated from recording on {self._format_timestamp()}',
'target_url': target_url or 'https://example.com',
'container_selector': self.container_selector,
'fields': [
{
'name': field_name,
'selector': selector,
'required': True
}
for field_name, selector in self.extracted_fields.items()
],
'pagination': {
'enabled': self.pagination_selector is not None,
'next_button_selector': self.pagination_selector or '',
'max_pages': 10
},
'output': {
'format': 'csv',
'filename': 'recorded_scraper.csv'
},
'notes': f'Generated from {len(self.actions)} recorded actions'
}
return config
def _format_timestamp(self) -> str:
"""Format current timestamp"""
from datetime import datetime
return datetime.now().strftime('%Y-%m-%d %H:%M')
class RecorderConfigGenerator:
"""Generates configurations from recorded browser sessions"""
def __init__(self, recordings_dir: str = 'data/recordings'):
self.recordings_dir = Path(recordings_dir)
self.recordings_dir.mkdir(parents=True, exist_ok=True)
def save_recording(self, recording_id: str, actions: List[Dict]) -> str:
"""Save recorded actions to file"""
filepath = self.recordings_dir / f"{recording_id}.json"
recording_data = {
'recording_id': recording_id,
'actions': actions,
'timestamp': actions[0]['timestamp'] if actions else None,
'action_count': len(actions)
}
with open(filepath, 'w') as f:
json.dump(recording_data, f, indent=2)
return str(filepath)
def load_recording(self, recording_id: str) -> Dict:
"""Load recorded actions from file"""
filepath = self.recordings_dir / f"{recording_id}.json"
if not filepath.exists():
raise FileNotFoundError(f"Recording {recording_id} not found")
with open(filepath, 'r') as f:
return json.load(f)
def generate_config_from_recording(self, recording_id: str) -> Dict[str, Any]:
"""Generate scraper config from saved recording"""
recording = self.load_recording(recording_id)
actions = recording['actions']
analyzer = RecordingAnalyzer(actions)
config = analyzer.analyze()
return config
def generate_config_from_actions(self, actions: List[Dict]) -> Dict[str, Any]:
"""Generate scraper config directly from actions"""
analyzer = RecordingAnalyzer(actions)
config = analyzer.analyze()
return config
def validate_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Validate generated configuration"""
errors = []
warnings = []
# Check required fields
if not config.get('target_url'):
errors.append("Target URL is required")
if not config.get('container_selector'):
errors.append("Container selector is required")
if not config.get('fields') or len(config['fields']) == 0:
errors.append("At least one field is required")
# Check field selectors
for field in config.get('fields', []):
if not field.get('selector'):
errors.append(f"Field '{field.get('name')}' missing selector")
# Warnings
if config.get('pagination', {}).get('enabled') and \
not config['pagination'].get('next_button_selector'):
warnings.append("Pagination enabled but no next button selector")
return {
'valid': len(errors) == 0,
'errors': errors,
'warnings': warnings,
'config': config
}
def preview_data(self, config: Dict[str, Any]) -> List[Dict]:
"""Generate preview data based on configuration"""
fields = config.get('fields', [])
field_names = [f['name'] for f in fields]
# Generate sample data
preview = []
for i in range(3):
item = {field: f"Sample {field} {i+1}" for field in field_names}
preview.append(item)
return preview
if __name__ == '__main__':
# Example usage
sample_actions = [
{
'type': 'navigate',
'selector': 'https://quotes.toscrape.com/',
'timestamp': 1699564800000
},
{
'type': 'container',
'selector': '.quote',
'timestamp': 1699564801000
},
{
'type': 'extract',
'selector': '.text',
'field': 'quote_text',
'data': 'The world as we have created it...',
'timestamp': 1699564802000,
'tag_name': 'span',
'attributes': {'class': 'text'}
},
{
'type': 'extract',
'selector': '.author',
'field': 'author',
'data': 'Albert Einstein',
'timestamp': 1699564803000,
'tag_name': 'small',
'attributes': {'class': 'author'}
}
]
generator = RecorderConfigGenerator()
config = generator.generate_config_from_actions(sample_actions)
validation = generator.validate_config(config)
print("=" * 60)
print("GENERATED CONFIGURATION")
print("=" * 60)
print(json.dumps(config, indent=2))
print("\n" + "=" * 60)
print("VALIDATION RESULTS")
print("=" * 60)
print(f"Valid: {validation['valid']}")
if validation['errors']:
print(f"Errors: {validation['errors']}")
if validation['warnings']:
print(f"Warnings: {validation['warnings']}")