-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathjusthtml.html
More file actions
999 lines (851 loc) · 32.1 KB
/
justhtml.html
File metadata and controls
999 lines (851 loc) · 32.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JustHTML Playground - HTML5 Parser</title>
<style>
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
margin: 0;
padding: 20px;
background: #f5f5f5;
color: #333;
min-height: 100vh;
}
h1 {
text-align: center;
color: #2c3e50;
margin-bottom: 5px;
}
.subtitle {
text-align: center;
color: #666;
margin-bottom: 20px;
}
.subtitle a {
color: #3498db;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.status-bar {
background: #fff;
padding: 10px 15px;
border-radius: 8px;
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.status {
font-size: 14px;
padding: 4px 12px;
border-radius: 4px;
background: #f39c12;
color: #fff;
}
.status.ready {
background: #27ae60;
}
.status.error {
background: #e74c3c;
}
.input-section {
background: #fff;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.input-tabs {
display: flex;
gap: 10px;
margin-bottom: 15px;
}
.tab-btn {
background: #3498db;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
.tab-btn.active {
background: #2c3e50;
color: #fff;
}
.tab-btn:hover:not(.active) {
background: #2980b9;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.url-input-row {
display: flex;
gap: 10px;
}
.url-input-row input {
flex: 1;
}
input[type="text"], input[type="url"] {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 16px;
}
input:focus {
border-color: #3498db;
outline: none;
box-shadow: 0 0 0 3px rgba(52,152,219,0.2);
}
textarea {
width: 100%;
height: 200px;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
font-size: 14px;
resize: vertical;
line-height: 1.5;
}
textarea:focus {
border-color: #3498db;
outline: none;
box-shadow: 0 0 0 3px rgba(52,152,219,0.2);
}
.mode-section {
background: #fff;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.mode-section h3 {
margin-top: 0;
margin-bottom: 15px;
color: #2c3e50;
}
.mode-tabs {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-bottom: 15px;
}
.mode-btn {
background: #ecf0f1;
color: #2c3e50;
border: none;
padding: 10px 16px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
.mode-btn.active {
background: #9b59b6;
color: #fff;
}
.mode-btn:hover:not(.active) {
background: #dde4e6;
}
.mode-options {
display: none;
margin-bottom: 15px;
}
.mode-options.active {
display: block;
}
.mode-options label {
display: block;
margin-bottom: 5px;
font-weight: 500;
color: #555;
}
.selector-input {
display: flex;
gap: 10px;
}
.selector-input input {
flex: 1;
}
button {
background: #3498db;
color: #fff;
border: none;
padding: 12px 24px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
transition: background 0.2s;
}
button:hover {
background: #2980b9;
}
button:disabled {
background: #bdc3c7;
cursor: not-allowed;
}
.run-btn {
background: #27ae60;
}
.run-btn:hover {
background: #229954;
}
.output-section {
background: #fff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.output-header {
background: #2c3e50;
color: #fff;
padding: 12px 20px;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
}
.output-content {
padding: 20px;
min-height: 200px;
max-height: 500px;
overflow: auto;
font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
font-size: 14px;
line-height: 1.6;
white-space: pre-wrap;
background: #fafafa;
}
.output-content.error {
background: #fdf2f2;
color: #c0392b;
}
.examples-section {
background: #fff;
border-radius: 8px;
padding: 20px;
margin-top: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.examples-section h3 {
margin-top: 0;
margin-bottom: 15px;
color: #2c3e50;
}
.example-buttons {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.example-btn {
background: #ecf0f1;
color: #2c3e50;
}
.example-btn:hover {
background: #dde4e6;
}
.info-box {
background: #e8f4fd;
border-left: 4px solid #3498db;
padding: 15px;
margin-top: 20px;
border-radius: 0 8px 8px 0;
font-size: 14px;
}
.info-box a {
color: #3498db;
}
.match-count {
background: #27ae60;
color: #fff;
padding: 4px 10px;
border-radius: 12px;
font-size: 12px;
}
@media (max-width: 600px) {
body {
padding: 10px;
}
.input-tabs, .mode-tabs {
flex-direction: column;
}
.tab-btn, .mode-btn {
width: 100%;
}
.url-input-row {
flex-direction: column;
}
.selector-input {
flex-direction: column;
}
.example-buttons {
flex-direction: column;
}
.example-btn {
width: 100%;
}
}
</style>
</head>
<body>
<div class="container">
<h1>JustHTML Playground</h1>
<p class="subtitle">A pure Python HTML5 parser that just works - <a href="https://github.com/EmilStenstrom/justhtml" target="_blank">GitHub</a></p>
<div class="status-bar">
<span>Python Environment</span>
<span id="status" class="status">Loading Pyodide...</span>
</div>
<div class="input-section">
<div class="input-tabs">
<button class="tab-btn active" data-tab="paste">Paste HTML</button>
<button class="tab-btn" data-tab="url">Fetch from URL</button>
</div>
<div id="paste-tab" class="tab-content active">
<textarea id="html-input" placeholder="Paste your HTML here..."><!DOCTYPE html>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/" class="active">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h1>Welcome to JustHTML</h1>
<p class="intro">A <strong>pure Python</strong> HTML5 parser.</p>
<p>It passes all 9,200+ official html5lib tests.</p>
</article>
<aside>
<h2>Features</h2>
<ul>
<li>CSS Selectors</li>
<li>Tree Traversal</li>
<li>Pretty Printing</li>
</ul>
</aside>
</main>
<footer>
<p>© 2024 Example</p>
</footer>
</body>
</html></textarea>
</div>
<div id="url-tab" class="tab-content">
<div class="url-input-row">
<input type="url" id="url-input" placeholder="https://example.com (must support CORS)">
<button id="fetch-btn" disabled>Fetch</button>
</div>
<p style="font-size: 12px; color: #888; margin-top: 8px;">
Note: The URL must support CORS. Try APIs or sites with permissive CORS headers.
</p>
</div>
</div>
<div class="mode-section">
<h3>Playground Mode</h3>
<div class="mode-tabs">
<button class="mode-btn active" data-mode="selector">CSS Selector Query</button>
<button class="mode-btn" data-mode="pretty">Pretty Print HTML</button>
<button class="mode-btn" data-mode="tree">Tree Structure</button>
<button class="mode-btn" data-mode="stream">Stream Events</button>
<button class="mode-btn" data-mode="text">Extract Text</button>
<button class="mode-btn" data-mode="markdown">To Markdown</button>
</div>
<div id="selector-options" class="mode-options active">
<label for="selector-input">CSS Selector:</label>
<div class="selector-input">
<input type="text" id="selector-input" placeholder="e.g., p.intro, nav ul li a, h1, h2, h3" value="p">
<button id="run-btn" class="run-btn" disabled>Run Query</button>
</div>
</div>
<div id="pretty-options" class="mode-options">
<button id="pretty-btn" class="run-btn" disabled>Pretty Print</button>
</div>
<div id="tree-options" class="mode-options">
<button id="tree-btn" class="run-btn" disabled>Show Tree</button>
</div>
<div id="stream-options" class="mode-options">
<button id="stream-btn" class="run-btn" disabled>Show Events</button>
</div>
<div id="text-options" class="mode-options">
<label for="text-selector-input">CSS Selector (optional - leave empty for whole document):</label>
<div class="selector-input">
<input type="text" id="text-selector-input" placeholder="e.g., article, main, .content (or leave empty)">
<button id="text-btn" class="run-btn" disabled>Extract Text</button>
</div>
</div>
<div id="markdown-options" class="mode-options">
<label for="markdown-selector-input">CSS Selector (optional - leave empty for whole document):</label>
<div class="selector-input">
<input type="text" id="markdown-selector-input" placeholder="e.g., article, main, .content (or leave empty)">
<button id="markdown-btn" class="run-btn" disabled>Convert to Markdown</button>
</div>
</div>
</div>
<div class="output-section">
<div class="output-header">
<span>Output</span>
<span id="match-count" class="match-count" style="display: none;">0 matches</span>
</div>
<div id="output" class="output-content">Results will appear here...</div>
</div>
<div class="examples-section">
<h3>Example Selectors</h3>
<div class="example-buttons">
<button class="example-btn" data-selector="a">All Links (a)</button>
<button class="example-btn" data-selector="p.intro">Intro Paragraphs (p.intro)</button>
<button class="example-btn" data-selector="nav > ul > li">Nav Items (nav > ul > li)</button>
<button class="example-btn" data-selector="h1, h2, h3">All Headings (h1, h2, h3)</button>
<button class="example-btn" data-selector="[href]">Elements with href</button>
<button class="example-btn" data-selector="li:first-child">First List Items</button>
</div>
</div>
<div class="info-box">
<strong>About JustHTML:</strong> A pure Python HTML5 parser with zero dependencies.
It implements the official WHATWG HTML5 specification exactly and passes all 9,200+ tests
in the official html5lib-tests suite.
<a href="https://github.com/EmilStenstrom/justhtml" target="_blank">Learn more on GitHub</a>
</div>
</div>
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js"></script>
<script>
let pyodide = null;
const statusEl = document.getElementById('status');
const outputEl = document.getElementById('output');
const matchCountEl = document.getElementById('match-count');
const htmlInputEl = document.getElementById('html-input');
const urlInputEl = document.getElementById('url-input');
const selectorInputEl = document.getElementById('selector-input');
const textSelectorInputEl = document.getElementById('text-selector-input');
const markdownSelectorInputEl = document.getElementById('markdown-selector-input');
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
btn.classList.add('active');
document.getElementById(`${btn.dataset.tab}-tab`).classList.add('active');
});
});
// Mode switching
document.querySelectorAll('.mode-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.mode-options').forEach(o => o.classList.remove('active'));
btn.classList.add('active');
document.getElementById(`${btn.dataset.mode}-options`).classList.add('active');
});
});
// Example selector buttons
document.querySelectorAll('.example-btn').forEach(btn => {
btn.addEventListener('click', () => {
selectorInputEl.value = btn.dataset.selector;
// Switch to selector mode
document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.mode-options').forEach(o => o.classList.remove('active'));
document.querySelector('[data-mode="selector"]').classList.add('active');
document.getElementById('selector-options').classList.add('active');
runQuery();
});
});
async function initPyodide() {
try {
statusEl.textContent = 'Loading Pyodide...';
statusEl.className = 'status';
pyodide = await loadPyodide();
statusEl.textContent = 'Installing justhtml...';
await pyodide.loadPackage('micropip');
await pyodide.runPythonAsync(`
import micropip
await micropip.install('justhtml')
`);
// Set up helper functions
await pyodide.runPythonAsync(`
from justhtml import JustHTML, stream
import json
def query_html(html_str, selector):
"""Query HTML with a CSS selector and return results."""
doc = JustHTML(html_str)
results = doc.query(selector)
output = []
for node in results:
output.append(node.to_html())
return {
'count': len(results),
'results': output
}
def pretty_print_html(html_str):
"""Pretty print HTML."""
doc = JustHTML(html_str)
return doc.root.to_html()
def get_tree_structure(html_str, indent=0):
"""Get the tree structure of the HTML."""
doc = JustHTML(html_str)
def format_node(node, depth=0):
prefix = " " * depth
lines = []
name = getattr(node, 'name', None)
if name:
attrs = getattr(node, 'attrs', None) or {}
if attrs:
attr_str = " ".join(f'{k}="{v}"' for k, v in attrs.items())
lines.append(f"{prefix}<{name} {attr_str}>")
else:
lines.append(f"{prefix}<{name}>")
children = getattr(node, 'children', None) or []
for child in children:
lines.extend(format_node(child, depth + 1))
else:
# Text node
text = str(node).strip()
if text:
# Truncate long text
if len(text) > 50:
text = text[:47] + "..."
lines.append(f'{prefix}"{text}"')
return lines
lines = []
root_children = getattr(doc.root, 'children', None) or []
for child in root_children:
lines.extend(format_node(child, 0))
return "\\n".join(lines)
def get_stream_events(html_str):
"""Get streaming events from HTML parsing."""
events = []
for event, data in stream(html_str):
if event == "start":
tag, attrs = data
if attrs:
attr_str = " ".join(f'{k}="{v}"' for k, v in attrs.items())
events.append(f"START: <{tag} {attr_str}>")
else:
events.append(f"START: <{tag}>")
elif event == "end":
events.append(f"END: </{data}>")
elif event == "text":
text = data.strip()
if text:
if len(text) > 60:
text = text[:57] + "..."
events.append(f'TEXT: "{text}"')
elif event == "comment":
events.append(f"COMMENT: <!--{data}-->")
elif event == "doctype":
events.append(f"DOCTYPE: {data}")
return "\\n".join(events)
def extract_text(html_str, selector=None):
"""Extract text from HTML, optionally filtered by CSS selector."""
doc = JustHTML(html_str)
if selector and selector.strip():
results = doc.query(selector)
if not results:
return {
'count': 0,
'results': []
}
output = []
for node in results:
text = node.to_text()
if text.strip():
output.append(text)
return {
'count': len(results),
'results': output
}
else:
# Whole document
return {
'count': 1,
'results': [doc.to_text()]
}
def convert_to_markdown(html_str, selector=None):
"""Convert HTML to Markdown, optionally filtered by CSS selector."""
doc = JustHTML(html_str)
if selector and selector.strip():
results = doc.query(selector)
if not results:
return {
'count': 0,
'results': []
}
output = []
for node in results:
md = node.to_markdown()
if md.strip():
output.append(md)
return {
'count': len(results),
'results': output
}
else:
# Whole document
return {
'count': 1,
'results': [doc.to_markdown()]
}
`);
statusEl.textContent = 'Ready';
statusEl.className = 'status ready';
// Enable buttons
document.querySelectorAll('button').forEach(btn => {
btn.disabled = false;
});
} catch (error) {
statusEl.textContent = 'Error loading';
statusEl.className = 'status error';
outputEl.textContent = `Failed to initialize: ${error.message}`;
outputEl.className = 'output-content error';
}
}
function getHtmlInput() {
const pasteTab = document.getElementById('paste-tab');
if (pasteTab.classList.contains('active')) {
return htmlInputEl.value;
}
return htmlInputEl.value; // Use whatever was last fetched/pasted
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
async function runQuery() {
if (!pyodide) return;
const html = getHtmlInput();
const selector = selectorInputEl.value.trim();
if (!selector) {
outputEl.textContent = 'Please enter a CSS selector';
matchCountEl.style.display = 'none';
return;
}
try {
const escapedHtml = html.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
const escapedSelector = selector.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
const result = await pyodide.runPythonAsync(`
html = """${escapedHtml}"""
selector = "${escapedSelector}"
query_html(html, selector)
`);
const jsResult = result.toJs();
const count = jsResult.get('count');
const results = jsResult.get('results');
matchCountEl.textContent = `${count} match${count !== 1 ? 'es' : ''}`;
matchCountEl.style.display = 'inline';
if (count === 0) {
outputEl.textContent = `No elements match the selector "${selector}"`;
outputEl.className = 'output-content';
} else {
const resultsArray = Array.from(results);
outputEl.textContent = resultsArray.join('\n\n---\n\n');
outputEl.className = 'output-content';
}
} catch (error) {
let errorMsg = error.message;
if (errorMsg.includes('SelectorError')) {
const match = errorMsg.match(/SelectorError[:\s]*([\s\S]*?)(?:\n\s*at |$)/);
if (match) errorMsg = 'Selector Error: ' + match[1].trim();
}
outputEl.textContent = errorMsg;
outputEl.className = 'output-content error';
matchCountEl.style.display = 'none';
}
}
async function prettyPrint() {
if (!pyodide) return;
const html = getHtmlInput();
try {
const escapedHtml = html.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
const result = await pyodide.runPythonAsync(`
html = """${escapedHtml}"""
pretty_print_html(html)
`);
outputEl.textContent = result;
outputEl.className = 'output-content';
matchCountEl.style.display = 'none';
} catch (error) {
outputEl.textContent = error.message;
outputEl.className = 'output-content error';
matchCountEl.style.display = 'none';
}
}
async function showTree() {
if (!pyodide) return;
const html = getHtmlInput();
try {
const escapedHtml = html.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
const result = await pyodide.runPythonAsync(`
html = """${escapedHtml}"""
get_tree_structure(html)
`);
outputEl.textContent = result;
outputEl.className = 'output-content';
matchCountEl.style.display = 'none';
} catch (error) {
outputEl.textContent = error.message;
outputEl.className = 'output-content error';
matchCountEl.style.display = 'none';
}
}
async function showStreamEvents() {
if (!pyodide) return;
const html = getHtmlInput();
try {
const escapedHtml = html.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
const result = await pyodide.runPythonAsync(`
html = """${escapedHtml}"""
get_stream_events(html)
`);
outputEl.textContent = result;
outputEl.className = 'output-content';
matchCountEl.style.display = 'none';
} catch (error) {
outputEl.textContent = error.message;
outputEl.className = 'output-content error';
matchCountEl.style.display = 'none';
}
}
async function extractText() {
if (!pyodide) return;
const html = getHtmlInput();
const selector = textSelectorInputEl.value.trim();
try {
const escapedHtml = html.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
const escapedSelector = selector ? selector.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '';
const result = await pyodide.runPythonAsync(`
html = """${escapedHtml}"""
selector = "${escapedSelector}" if "${escapedSelector}" else None
extract_text(html, selector)
`);
const jsResult = result.toJs();
const count = jsResult.get('count');
const results = jsResult.get('results');
if (selector) {
matchCountEl.textContent = `${count} match${count !== 1 ? 'es' : ''}`;
matchCountEl.style.display = 'inline';
} else {
matchCountEl.textContent = 'Whole document';
matchCountEl.style.display = 'inline';
}
if (count === 0) {
outputEl.textContent = `No elements match the selector "${selector}"`;
outputEl.className = 'output-content';
} else {
const resultsArray = Array.from(results);
outputEl.textContent = resultsArray.join('\n\n---\n\n');
outputEl.className = 'output-content';
}
} catch (error) {
outputEl.textContent = error.message;
outputEl.className = 'output-content error';
matchCountEl.style.display = 'none';
}
}
async function convertToMarkdown() {
if (!pyodide) return;
const html = getHtmlInput();
const selector = markdownSelectorInputEl.value.trim();
try {
const escapedHtml = html.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"');
const escapedSelector = selector ? selector.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '';
const result = await pyodide.runPythonAsync(`
html = """${escapedHtml}"""
selector = "${escapedSelector}" if "${escapedSelector}" else None
convert_to_markdown(html, selector)
`);
const jsResult = result.toJs();
const count = jsResult.get('count');
const results = jsResult.get('results');
if (selector) {
matchCountEl.textContent = `${count} match${count !== 1 ? 'es' : ''}`;
matchCountEl.style.display = 'inline';
} else {
matchCountEl.textContent = 'Whole document';
matchCountEl.style.display = 'inline';
}
if (count === 0) {
outputEl.textContent = `No elements match the selector "${selector}"`;
outputEl.className = 'output-content';
} else {
const resultsArray = Array.from(results);
outputEl.textContent = resultsArray.join('\n\n---\n\n');
outputEl.className = 'output-content';
}
} catch (error) {
outputEl.textContent = error.message;
outputEl.className = 'output-content error';
matchCountEl.style.display = 'none';
}
}
async function fetchUrl() {
const url = urlInputEl.value.trim();
if (!url) {
alert('Please enter a URL');
return;
}
try {
document.getElementById('fetch-btn').disabled = true;
document.getElementById('fetch-btn').textContent = 'Fetching...';
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const html = await response.text();
htmlInputEl.value = html;
// Switch to paste tab to show the fetched HTML
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
document.querySelector('[data-tab="paste"]').classList.add('active');
document.getElementById('paste-tab').classList.add('active');
outputEl.textContent = `Fetched ${html.length} characters from ${url}. Select a mode above to process.`;
outputEl.className = 'output-content';
} catch (error) {
outputEl.textContent = `Failed to fetch URL: ${error.message}\n\nNote: The target URL must have CORS headers that allow cross-origin requests.`;
outputEl.className = 'output-content error';
} finally {
document.getElementById('fetch-btn').disabled = false;
document.getElementById('fetch-btn').textContent = 'Fetch';
}
}
// Event listeners
document.getElementById('run-btn').addEventListener('click', runQuery);
document.getElementById('pretty-btn').addEventListener('click', prettyPrint);
document.getElementById('tree-btn').addEventListener('click', showTree);
document.getElementById('stream-btn').addEventListener('click', showStreamEvents);
document.getElementById('text-btn').addEventListener('click', extractText);
document.getElementById('markdown-btn').addEventListener('click', convertToMarkdown);
document.getElementById('fetch-btn').addEventListener('click', fetchUrl);
// Run query on Enter in selector inputs
selectorInputEl.addEventListener('keypress', (e) => {
if (e.key === 'Enter') runQuery();
});
textSelectorInputEl.addEventListener('keypress', (e) => {
if (e.key === 'Enter') extractText();
});
markdownSelectorInputEl.addEventListener('keypress', (e) => {
if (e.key === 'Enter') convertToMarkdown();
});
// Initialize
initPyodide();
</script>
</body>
</html>