Repository navigation
Expand file tree
/
Copy pathWebContentExtractor.py
More file actions
2344 lines (2135 loc) · 87.9 KB
/
Copy pathWebContentExtractor.py
File metadata and controls
2344 lines (2135 loc) · 87.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
# -*- coding: utf-8 -*-
"""
Web Content Extractor Pro v11.1 - Bug修复版
基于PyQt5和BeautifulSoup开发,支持多平台内容提取、多格式输出、数学公式处理
github网址: https://github.com/lyp0746
QQ邮箱: 1610369302@qq.com
作者: LYP
v11.1 修复:
- [修复] 菜鸟教程: 入口页面"XXX教程"不再丢失,作为第一篇章节插入
- [修复] 聚合文件名: 改为以第一篇文章标题命名
- [增强] PDF样式: 更专业的书籍排版 — 优化封面/目录/正文/代码块/页眉页脚
"""
import sys
import os
import re
import html as html_module
import warnings
import hashlib
import tempfile
import json
from pathlib import Path
from typing import List, Tuple, Optional, Dict, Set
from urllib.parse import urljoin, urlparse, quote
from dataclasses import dataclass, field
import time
from datetime import datetime
import requests
from bs4 import BeautifulSoup, NavigableString, Tag
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGroupBox, QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox,
QTextEdit, QFileDialog, QMessageBox
)
from PyQt5.QtCore import QThread, pyqtSignal, QSettings
from PyQt5.QtGui import QFont, QTextCursor
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", message="sipPyTypeDict")
try:
from weasyprint import HTML as WeasyHTML, CSS
from weasyprint.text.fonts import FontConfiguration
WEASY_AVAILABLE = True
except ImportError:
WEASY_AVAILABLE = False
# ==================== 数据结构 ====================
@dataclass
class Article:
"""文章数据"""
title: str
url: str
level: int = 1 # 层级 (1=章, 2=节, 3=小节)
content: str = "" # Markdown 内容
html_content: str = "" # HTML 内容
author: str = ""
date: str = ""
category: str = ""
anchor: str = "" # 唯一锚点ID (用于目录跳转)
children: List['Article'] = field(default_factory=list) # 子页面内容
# ==================== 公式存储 ====================
class MathStore:
"""独立的公式存储,避免公式在HTML/Markdown转换中被破坏"""
def __init__(self):
self._formulas: List[Tuple[str, bool]] = [] # (latex, is_display)
def store(self, latex: str, is_display: bool) -> str:
"""存储一个公式,返回占位符"""
idx = len(self._formulas)
self._formulas.append((latex, is_display))
tag = 'DISPLAY' if is_display else 'INLINE'
return f'§MATH_{tag}_{idx}§'
def restore_markdown(self, text: str) -> str:
"""还原为Markdown格式的LaTeX公式"""
for idx, (latex, is_display) in enumerate(self._formulas):
if is_display:
text = text.replace(f'§MATH_DISPLAY_{idx}§', f'\n\n$$\n{latex}\n$$\n\n')
else:
text = text.replace(f'§MATH_INLINE_{idx}§', f'${latex}$')
return text
def restore_html(self, text: str) -> str:
"""还原为HTML格式,保留原始LaTeX供MathJax渲染"""
for idx, (latex, is_display) in enumerate(self._formulas):
escaped = html_module.escape(latex)
if is_display:
text = text.replace(
f'§MATH_DISPLAY_{idx}§',
f'<div class="math-display">$${escaped}$$</div>')
else:
text = text.replace(
f'§MATH_INLINE_{idx}§',
f'<span class="math-inline">${escaped}$</span>')
return text
def restore_pdf(self, text: str) -> str:
"""还原为PDF可渲染格式(Unicode近似 + 原始LaTeX注释)"""
for idx, (latex, is_display) in enumerate(self._formulas):
readable = _latex_to_readable(latex)
escaped_readable = html_module.escape(readable)
escaped_latex = html_module.escape(latex)
if is_display:
text = text.replace(
f'§MATH_DISPLAY_{idx}§',
f'<div class="math-display" title="{escaped_latex}">'
f'{escaped_readable}</div>')
else:
text = text.replace(
f'§MATH_INLINE_{idx}§',
f'<span class="math-inline" title="{escaped_latex}">'
f'{escaped_readable}</span>')
return text
@property
def empty(self) -> bool:
return len(self._formulas) == 0
def _latex_to_readable(latex: str) -> str:
"""LaTeX → 可读Unicode文本 (用于PDF降级显示)"""
text = latex
_REPLACEMENTS = [
(r'\\frac\{([^}]*)\}\{([^}]*)\}', r'(\1)/(\2)'),
(r'\\sqrt\[([^\]]*)\]\{([^}]*)\}', r'(\2)^(1/\1)'),
(r'\\sqrt\{([^}]*)\}', r'√(\1)'),
(r'\\overline\{([^}]*)\}', r'\1̄'),
(r'\\hat\{([^}]*)\}', r'\1̂'),
(r'\\vec\{([^}]*)\}', r'\1⃗'),
(r'\\dot\{([^}]*)\}', r'\1̇'),
(r'\\ddot\{([^}]*)\}', r'\1̈'),
(r'\\tilde\{([^}]*)\}', r'\1̃'),
(r'\\bar\{([^}]*)\}', r'\1̄'),
(r'\^{([^}]*)}', r'^(\1)'),
(r'_{([^}]*)}', r'_(\1)'),
(r'\^(\w)', r'^\1'),
(r'_(\w)', r'_\1'),
(r'\\alpha', 'α'), (r'\\beta', 'β'), (r'\\gamma', 'γ'),
(r'\\delta', 'δ'), (r'\\epsilon', 'ε'), (r'\\varepsilon', 'ε'),
(r'\\zeta', 'ζ'), (r'\\eta', 'η'), (r'\\theta', 'θ'),
(r'\\vartheta', 'ϑ'), (r'\\iota', 'ι'), (r'\\kappa', 'κ'),
(r'\\lambda', 'λ'), (r'\\mu', 'μ'), (r'\\nu', 'ν'),
(r'\\xi', 'ξ'), (r'\\pi', 'π'), (r'\\varpi', 'ϖ'),
(r'\\rho', 'ρ'), (r'\\varrho', 'ϱ'), (r'\\sigma', 'σ'),
(r'\\varsigma', 'ς'), (r'\\tau', 'τ'), (r'\\upsilon', 'υ'),
(r'\\phi', 'φ'), (r'\\varphi', 'ϕ'), (r'\\chi', 'χ'),
(r'\\psi', 'ψ'), (r'\\omega', 'ω'),
(r'\\Gamma', 'Γ'), (r'\\Delta', 'Δ'), (r'\\Theta', 'Θ'),
(r'\\Lambda', 'Λ'), (r'\\Xi', 'Ξ'), (r'\\Pi', 'Π'),
(r'\\Sigma', 'Σ'), (r'\\Upsilon', 'Υ'), (r'\\Phi', 'Φ'),
(r'\\Psi', 'Ψ'), (r'\\Omega', 'Ω'),
(r'\\sum', '∑'), (r'\\prod', '∏'), (r'\\coprod', '∐'),
(r'\\int', '∫'), (r'\\iint', '∬'), (r'\\iiint', '∭'),
(r'\\oint', '∮'),
(r'\\infty', '∞'), (r'\\nabla', '∇'), (r'\\partial', '∂'),
(r'\\leq', '≤'), (r'\\le', '≤'), (r'\\geq', '≥'), (r'\\ge', '≥'),
(r'\\neq', '≠'), (r'\\ne', '≠'), (r'\\approx', '≈'),
(r'\\equiv', '≡'), (r'\\sim', '∼'), (r'\\simeq', '≃'),
(r'\\cong', '≅'), (r'\\propto', '∝'),
(r'\\ll', '≪'), (r'\\gg', '≫'),
(r'\\times', '×'), (r'\\div', '÷'), (r'\\cdot', '·'),
(r'\\pm', '±'), (r'\\mp', '∓'), (r'\\circ', '∘'),
(r'\\oplus', '⊕'), (r'\\otimes', '⊗'),
(r'\\rightarrow', '→'), (r'\\to', '→'),
(r'\\leftarrow', '←'), (r'\\gets', '←'),
(r'\\Rightarrow', '⇒'), (r'\\Leftarrow', '⇐'),
(r'\\leftrightarrow', '↔'), (r'\\Leftrightarrow', '⇔'),
(r'\\mapsto', '↦'), (r'\\uparrow', '↑'), (r'\\downarrow', '↓'),
(r'\\forall', '∀'), (r'\\exists', '∃'), (r'\\nexists', '∄'),
(r'\\neg', '¬'), (r'\\land', '∧'), (r'\\lor', '∨'),
(r'\\in', '∈'), (r'\\notin', '∉'), (r'\\ni', '∋'),
(r'\\subset', '⊂'), (r'\\supset', '⊃'),
(r'\\subseteq', '⊆'), (r'\\supseteq', '⊇'),
(r'\\cup', '∪'), (r'\\cap', '∩'),
(r'\\emptyset', '∅'), (r'\\varnothing', '∅'),
(r'\\ldots', '…'), (r'\\cdots', '⋯'), (r'\\vdots', '⋮'), (r'\\ddots', '⋱'),
(r'\\quad', ' '), (r'\\qquad', ' '), (r'\\,', ' '), (r'\\;', ' '),
(r'\\!', ''),
(r'\\langle', '⟨'), (r'\\rangle', '⟩'),
(r'\\lfloor', '⌊'), (r'\\rfloor', '⌋'),
(r'\\lceil', '⌈'), (r'\\rceil', '⌉'),
(r'\\star', '⋆'), (r'\\bullet', '•'), (r'\\dagger', '†'),
(r'\\text\{([^}]*)\}', r'\1'),
(r'\\textbf\{([^}]*)\}', r'\1'),
(r'\\textit\{([^}]*)\}', r'\1'),
(r'\\mathrm\{([^}]*)\}', r'\1'),
(r'\\mathbf\{([^}]*)\}', r'\1'),
(r'\\mathit\{([^}]*)\}', r'\1'),
(r'\\mathcal\{([^}]*)\}', r'\1'),
(r'\\mathbb\{([^}]*)\}', r'\1'),
(r'\\operatorname\{([^}]*)\}', r'\1'),
(r'\\(sin|cos|tan|cot|sec|csc|arcsin|arccos|arctan|sinh|cosh|tanh'
r'|log|ln|exp|lim|sup|inf|max|min|det|dim|ker|gcd|deg|hom|arg)', r'\1'),
(r'\\left', ''), (r'\\right', ''),
(r'\\big', ''), (r'\\Big', ''), (r'\\bigg', ''), (r'\\Bigg', ''),
(r'\\[{}]', ''), (r'\{', '('), (r'\}', ')'),
(r'\\\\', '\n'), (r'&', ' '),
]
for pattern, repl in _REPLACEMENTS:
text = re.sub(pattern, repl, text)
text = re.sub(r'\\[a-zA-Z]+', '', text)
text = re.sub(r'\s+', ' ', text).strip()
return text if text else latex
# ==================== 工具函数 ====================
def _make_anchor(title: str, index: int = 0) -> str:
"""生成GitBook风格的锚点ID"""
anchor = re.sub(r'[^\w\u4e00-\u9fff]+', '-', title).strip('-').lower()
return f"chapter-{index}-{anchor}" if index else anchor
def _slugify(title: str) -> str:
"""生成安全文件名"""
s = re.sub(r'[\\/:*?"<>|]+', '_', title).strip()[:100]
# 如果标题为空或只包含特殊字符,使用"教程"而不是"文档"
if not s or re.match(r'^[_\s]+$', s):
return "教程"
return s
# ==================== 爬虫基类 ====================
class BaseCrawler:
"""爬虫基类 — 图片下载、HTML清理、公式处理、Markdown转换"""
IMG_ATTRS = ('src', 'data-src', 'data-original-src', 'data-original',
'data-actualsrc', 'data-lazy-src', 'data-echo',
'data-url', 'data-img')
def __init__(self):
self.headers = {
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/125.0.0.0 Safari/537.36'),
'Accept': ('text/html,application/xhtml+xml,application/xml;'
'q=0.9,image/avif,image/webp,*/*;q=0.8'),
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
}
self.session = requests.Session()
self.session.headers.update(self.headers)
self._img_cache: Dict[str, str] = {}
def fetch(self, url: str, retries: int = 2, **kwargs) -> requests.Response:
last_err = None
for attempt in range(retries + 1):
try:
resp = self.session.get(url, headers=self.headers, timeout=20, **kwargs)
resp.encoding = resp.apparent_encoding or 'utf-8'
return resp
except Exception as e:
last_err = e
if attempt < retries:
time.sleep(1 * (attempt + 1))
raise last_err
def fetch_soup(self, url: str) -> BeautifulSoup:
return BeautifulSoup(self.fetch(url).text, 'html.parser')
@staticmethod
def _get_img_src(img: Tag) -> str:
for attr in BaseCrawler.IMG_ATTRS:
val = img.get(attr, '')
if val and not val.startswith('data:'):
return val.strip()
srcset = img.get('srcset', '')
if srcset:
first = srcset.split(',')[0].strip().split()[0]
if first and not first.startswith('data:'):
return first
return ''
def download_image(self, url: str, img_dir: str, referer: str = '') -> str:
if not url or url.startswith('data:'):
return url
clean_url = url.split('#')[0]
if clean_url in self._img_cache:
return self._img_cache[clean_url]
for attempt in range(3):
try:
headers = self.headers.copy()
if referer:
headers['Referer'] = referer
resp = self.session.get(clean_url, headers=headers, timeout=20, stream=True)
if resp.status_code != 200:
return url
ct = resp.headers.get('content-type', '')
ext = '.png'
_EXT_MAP = {
'jpeg': '.jpg', 'jpg': '.jpg', 'png': '.png',
'gif': '.gif', 'webp': '.webp', 'svg+xml': '.svg',
'svg': '.svg', 'bmp': '.bmp', 'ico': '.ico',
}
for key, val in _EXT_MAP.items():
if key in ct:
ext = val
break
else:
path = urlparse(clean_url).path.lower()
for e in ('.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp'):
if e in path:
ext = e
break
name = f"img_{hashlib.md5(clean_url.encode()).hexdigest()[:12]}{ext}"
dest = os.path.join(img_dir, name)
data = b''
for chunk in resp.iter_content(8192):
data += chunk
if len(data) < 100:
return url
with open(dest, 'wb') as f:
f.write(data)
result = f"images/{name}"
self._img_cache[clean_url] = result
return result
except Exception as e:
if attempt == 2:
print(f"[IMG] 下载失败: {url} → {e}")
return url
time.sleep(0.5)
return url
_REMOVE_TAGS = frozenset(['script', 'style', 'iframe', 'noscript', 'link',
'meta', 'template', 'svg'])
_AD_PATTERNS = re.compile(
r'adsbygoogle|^ads?[-_]|sponsor|promo[-_]|^banner|popup|modal[-_]'
r'|overlay|recommend[-_]?box|comment[-_]?box|share[-_]?box'
r'|social[-_]?share|tooltip|mask[-_]|csdn-side-toolbar'
r'|follow[-_]?box|login[-_]?box|^footer$|cookie[-_]?notice',
re.I
)
def clean_html(self, soup: Tag) -> Tag:
for tag in soup.find_all(list(self._REMOVE_TAGS)):
tag.decompose()
for tag in soup.find_all(class_=self._AD_PATTERNS):
if len(tag.get_text(strip=True)) < 200:
tag.decompose()
for tag in soup.find_all(style=re.compile(r'display\s*:\s*none', re.I)):
tag.decompose()
for tag in soup.find_all(['div', 'span']):
if not tag.get_text(strip=True) and not tag.find('img'):
tag.decompose()
return soup
@staticmethod
def _extract_latex(elem: Tag) -> Optional[str]:
if not elem:
return None
html_str = str(elem)
m = re.search(
r'<annotation[^>]*encoding="application/x-tex"[^>]*>(.*?)</annotation>',
html_str, re.DOTALL)
if m:
return html_module.unescape(m.group(1).strip())
for attr in ('data-tex', 'data-latex', 'data-formula', 'data-math'):
v = elem.get(attr)
if v:
return v.strip()
alt = elem.get('alt', '')
if alt and ('\\' in alt or '$' in alt):
return alt.strip().strip('$')
aria = elem.get('aria-label')
if aria and '\\' in aria:
return aria.strip()
mathml = elem.find(class_='katex-mathml')
if mathml:
ann = mathml.find('annotation')
if ann and ann.string:
return ann.string.strip()
t = mathml.get_text(strip=True)
if t:
return t
text = elem.get_text(strip=True)
return text if text else None
@staticmethod
def _is_display(elem: Tag) -> bool:
classes = elem.get('class', [])
if isinstance(classes, str):
classes = classes.split()
class_str = ' '.join(classes)
if any(kw in class_str for kw in (
'display', 'block', 'katex-display', 'ql-display',
'MathJax_Display', 'mjx-chtml')):
return True
style = elem.get('style', '')
if 'display' in style and 'block' in style:
return True
if elem.name in ('div', 'p') and elem.find(class_=re.compile(r'katex|mathjax', re.I)):
children = [c for c in elem.children
if isinstance(c, Tag) or (isinstance(c, NavigableString) and c.strip())]
if len(children) == 1:
return True
return False
def process_math(self, content: Tag) -> Tuple[Tag, MathStore]:
store = MathStore()
for script in content.find_all('script', type=re.compile(r'math/tex')):
formula = (script.string or '').strip()
if not formula:
continue
is_disp = 'mode=display' in (script.get('type') or '')
ph = store.store(formula, is_disp)
script.replace_with(NavigableString(ph))
for elem in content.find_all(class_=re.compile(r'katex-display', re.I)):
latex = self._extract_latex(elem)
if latex:
elem.replace_with(NavigableString(store.store(latex, True)))
for elem in content.find_all(class_=re.compile(
r'^katex$|MathJax|math-tex|mathjax', re.I)):
latex = self._extract_latex(elem)
if latex:
elem.replace_with(NavigableString(
store.store(latex, self._is_display(elem))))
for text_node in list(content.find_all(string=True)):
s = str(text_node)
if '\\(' not in s and '\\[' not in s:
continue
changed = False
def _repl_disp(m):
nonlocal changed
changed = True
return store.store(m.group(1).strip(), True)
def _repl_inl(m):
nonlocal changed
changed = True
return store.store(m.group(1).strip(), False)
s = re.sub(r'\\\[(.*?)\\\]', _repl_disp, s, flags=re.DOTALL)
s = re.sub(r'\\\((.*?)\\\)', _repl_inl, s)
if changed:
text_node.replace_with(NavigableString(s))
for text_node in list(content.find_all(string=True)):
s = str(text_node)
if '$' not in s:
continue
changed = False
def _repl_dd(m):
nonlocal changed
inner = m.group(1).strip()
if '\\' in inner or '_' in inner or '^' in inner:
changed = True
return store.store(inner, True)
return m.group(0)
def _repl_ds(m):
nonlocal changed
inner = m.group(1).strip()
if '\\' in inner or '_' in inner or '^' in inner:
changed = True
return store.store(inner, False)
return m.group(0)
s = re.sub(r'\$\$(.*?)\$\$', _repl_dd, s, flags=re.DOTALL)
s = re.sub(r'(?<!\$)\$(?!\$)((?:[^$\\]|\\.)+?)\$(?!\$)', _repl_ds, s)
if changed:
text_node.replace_with(NavigableString(s))
return content, store
def process_content(self, content: Tag, article: Article,
download_images: bool, img_dir: str) -> MathStore:
content = self.clean_html(content)
self._extra_clean(content, article)
if download_images:
for img in content.find_all('img'):
src = self._get_img_src(img)
if src:
img_url = urljoin(article.url, src)
local = self.download_image(img_url, img_dir, article.url)
img['src'] = local
for attr in self.IMG_ATTRS:
if attr != 'src' and img.has_attr(attr):
del img[attr]
if img.has_attr('srcset'):
del img['srcset']
if not img.get('alt'):
img['alt'] = '图片'
content, math_store = self.process_math(content)
article.html_content = math_store.restore_html(str(content))
article.content = self._html_to_markdown(content, math_store)
return math_store
def _extra_clean(self, content: Tag, article: Article):
pass
def _html_to_markdown(self, content: Tag, math_store: MathStore) -> str:
result = self._elem_to_md(content, 0)
result = math_store.restore_markdown(result)
result = re.sub(r'\n{3,}', '\n\n', result)
result = re.sub(r'([^\n])\n([-*] |\d+\. )', r'\1\n\n\2', result)
return result.strip()
def _elem_to_md(self, elem, indent: int = 0) -> str:
if isinstance(elem, NavigableString):
s = str(elem)
if '§MATH_' in s:
return s
return re.sub(r'[ \t]+', ' ', s)
if not isinstance(elem, Tag):
return ''
tag = elem.name
if tag in self._REMOVE_TAGS:
return ''
if tag in ('h1', 'h2', 'h3', 'h4', 'h5', 'h6'):
t = elem.get_text(strip=True)
return f"\n\n{'#' * int(tag[1])} {t}\n\n" if t else ''
if tag == 'p':
inner = self._children_md(elem, indent).strip()
return f"\n\n{inner}\n\n" if inner else ''
if tag == 'img':
return self._img_md(elem)
if tag == 'figure':
parts = ''
img = elem.find('img')
if img:
parts = self._img_md(img)
cap = elem.find('figcaption')
if cap:
ct = cap.get_text(strip=True)
if ct:
parts += f"\n*{ct}*\n"
return f"\n{parts}\n" if parts else ''
if tag == 'picture':
img = elem.find('img')
return self._img_md(img) if img else ''
if tag == 'a':
img = elem.find('img')
if img:
return self._img_md(img)
href = (elem.get('href') or '').strip()
text = elem.get_text(strip=True)
if text and href and href != '#' and not href.startswith('javascript'):
return f"[{text}]({href})"
return text or ''
if tag == 'pre':
code = elem.find('code')
text = code.get_text() if code else elem.get_text()
lang = self._detect_lang(code or elem)
return f"\n\n```{lang}\n{text.rstrip()}\n```\n\n"
if tag == 'code' and (not elem.parent or elem.parent.name != 'pre'):
t = elem.get_text(strip=True)
if not t:
return ''
return f"`` {t} ``" if '`' in t else f"`{t}`"
if tag == 'blockquote':
inner = self._children_md(elem, indent).strip()
if not inner:
return ''
quoted = '\n'.join(f"> {line}" for line in inner.split('\n') if line.strip())
return f"\n\n{quoted}\n\n"
if tag in ('ul', 'ol'):
return self._list_md(elem, tag, indent)
if tag == 'li':
return self._children_md(elem, indent).strip()
if tag == 'table':
return self._table_md(elem)
if tag in ('strong', 'b'):
t = self._children_md(elem, indent).strip()
return f"**{t}**" if t else ''
if tag in ('em', 'i'):
t = self._children_md(elem, indent).strip()
return f"*{t}*" if t else ''
if tag in ('del', 's', 'strike'):
t = elem.get_text(strip=True)
return f"~~{t}~~" if t else ''
if tag in ('mark',):
t = self._children_md(elem, indent).strip()
return f"=={t}==" if t else ''
if tag in ('sub',):
t = elem.get_text(strip=True)
return f"~{t}~" if t else ''
if tag in ('sup',):
t = elem.get_text(strip=True)
return f"^{t}^" if t else ''
if tag == 'br':
return '\n'
if tag == 'hr':
return '\n\n---\n\n'
if tag == 'details':
summary = elem.find('summary')
s_text = summary.get_text(strip=True) if summary else '详情'
if summary:
summary.decompose()
inner = self._children_md(elem, indent).strip()
return f"\n\n<details>\n<summary>{s_text}</summary>\n\n{inner}\n\n</details>\n\n"
if tag == 'summary':
return ''
return self._children_md(elem, indent)
def _children_md(self, elem: Tag, indent: int) -> str:
return ''.join(self._elem_to_md(c, indent) for c in elem.children)
def _img_md(self, img: Tag) -> str:
src = self._get_img_src(img)
if not src:
return ''
alt = (img.get('alt') or '图片')
alt = alt.replace('[', '').replace(']', '').replace('\n', ' ').strip()[:80]
return f"\n\n\n\n"
@staticmethod
def _detect_lang(elem: Tag) -> str:
classes = elem.get('class', [])
if isinstance(classes, str):
classes = classes.split()
for cls in classes:
if cls.startswith('language-') or cls.startswith('lang-'):
return cls.split('-', 1)[1]
if cls.startswith('highlight-source-'):
return cls.replace('highlight-source-', '')
_KNOWN_LANGS = {
'python', 'java', 'cpp', 'c', 'javascript', 'js', 'html', 'css',
'sql', 'bash', 'shell', 'sh', 'go', 'rust', 'ruby', 'php', 'swift',
'kotlin', 'typescript', 'ts', 'json', 'xml', 'yaml', 'markdown',
'csharp', 'cs', 'scala', 'r', 'matlab', 'perl', 'lua', 'dart',
'objectivec', 'objc', 'groovy', 'powershell', 'dockerfile',
}
if cls.lower() in _KNOWN_LANGS:
return cls.lower()
return elem.get('data-lang', '') or elem.get('data-language', '') or ''
def _list_md(self, elem: Tag, list_type: str, indent: int) -> str:
lines = []
prefix_base = ' ' * indent
for idx, item in enumerate(elem.find_all('li', recursive=False), 1):
prefix = f"{prefix_base}{idx}. " if list_type == 'ol' else f"{prefix_base}- "
parts = []
for child in item.children:
if isinstance(child, Tag) and child.name in ('ul', 'ol'):
parts.append('\n' + self._list_md(child, child.name, indent + 1))
else:
parts.append(self._elem_to_md(child, indent + 1))
text = ''.join(parts).strip()
sub_lines = text.split('\n')
result = [prefix + sub_lines[0]]
continuation_indent = ' ' * (indent + 1)
for sl in sub_lines[1:]:
result.append((continuation_indent + sl) if sl.strip() else '')
lines.append('\n'.join(result))
return '\n\n' + '\n'.join(lines) + '\n\n'
def _table_md(self, table: Tag) -> str:
rows = table.find_all('tr')
if not rows:
return ''
all_rows = []
for row in rows:
cells = []
for c in row.find_all(['th', 'td']):
cell_text = c.get_text(strip=True).replace('|', '\\|').replace('\n', ' ')
cells.append(cell_text)
all_rows.append(cells)
if not all_rows:
return ''
max_cols = max(len(r) for r in all_rows)
for r in all_rows:
r.extend([''] * (max_cols - len(r)))
col_widths = [3] * max_cols
for r in all_rows:
for i, cell in enumerate(r):
col_widths[i] = max(col_widths[i], len(cell))
def fmt_row(cells):
return '| ' + ' | '.join(c.ljust(col_widths[i]) for i, c in enumerate(cells)) + ' |'
out = '\n\n' + fmt_row(all_rows[0]) + '\n'
out += '| ' + ' | '.join('-' * col_widths[i] for i in range(max_cols)) + ' |\n'
for row in all_rows[1:]:
out += fmt_row(row) + '\n'
return out + '\n'
# ==================== 菜鸟教程爬虫 ====================
class RunoobCrawler(BaseCrawler):
"""菜鸟教程爬虫 — 修复入口页丢失问题"""
_SKIP = frozenset(('/try/', '/quiz/', '/compile/', '/dict/',
'/user/', '/login', '/register', '/sitemap',
'.zip', '.pdf', '.exe', '.dmg', '.apk',
'javascript:', 'mailto:', 'tel:', '/note/', '/download/'))
def extract_tutorial_info(self, url: str) -> Tuple[str, List[Article]]:
soup = self.fetch_soup(url)
title = self._get_title(soup)
articles: List[Article] = []
seen: Set[str] = set()
domain = urlparse(url).netloc
# ★★★ 修复1: 先将入口页本身作为第一篇文章插入 ★★★
entry_url = url.rstrip('/')
seen.add(entry_url)
# 获取入口页的标题(通常是"XXX 教程")
entry_title = title # 使用页面标题(已经过滤了URL路径)
# 如果title为空或标题仍然不理想,尝试从h1获取
if not entry_title or len(entry_title) < 3:
h1 = soup.find('h1')
if h1:
h1_text = h1.get_text(strip=True)
# 检查h1内容是否是URL路径
if h1_text and not h1_text.endswith('.html') and not h1_text.endswith('.htm'):
entry_title = h1_text
# 如果h1为空或标题仍然不理想,尝试从content区域获取
if not entry_title or len(entry_title) < 3:
content = soup.find('div', id='content') or soup.find('div', class_='article-intro')
if content:
content_h1 = content.find('h1')
if content_h1:
h1_text = content_h1.get_text(strip=True)
# 检查h1内容是否是URL路径
if h1_text and not h1_text.endswith('.html') and not h1_text.endswith('.htm'):
entry_title = h1_text
# 清理菜鸟教程后缀
entry_title = re.sub(r'\s*[-|_–—]?\s*菜鸟教程.*', '', entry_title).strip()
# 如果标题为空,使用URL路径作为标题
if not entry_title:
path = urlparse(url).path
entry_title = path.split('/')[-1] or "教程"
# 确保标题不为空
if not entry_title:
entry_title = "教程"
# 入口页作为第1章
articles.append(Article(entry_title, entry_url, level=1))
# 侧边栏
sidebar = (soup.find('div', id='leftcolumn') or
soup.find('div', class_='design-left') or
soup.find('div', id='sidebar') or
soup.find('div', class_=re.compile(r'sidebar|left[-_]?col|menu', re.I)))
if sidebar:
self._walk_sidebar(sidebar, articles, seen, url, domain, 1)
# 内容区域补充
if len(articles) < 4: # 改为4,因为第一篇已加入
content = (soup.find('div', id='content') or
soup.find('div', class_='article-intro') or
soup.find('div', class_='article-body'))
if content:
self._extract_links(content, articles, seen, url, domain)
# 嵌套页面展开
articles = self._expand_nested(articles, seen, domain)
# 兜底
if len(articles) <= 1:
for a in soup.find_all('a', href=True):
self._try_add(a, articles, seen, url, domain)
return title, articles
def _expand_nested(self, articles: List[Article],
seen: Set[str], domain: str,
depth: int = 0) -> List[Article]:
if depth > 3:
return articles
expanded = []
for art in articles:
expanded.append(art)
try:
soup = self.fetch_soup(art.url)
content = (soup.find('div', id='content') or
soup.find('div', class_='article-intro'))
if not content:
continue
links = content.find_all('a', href=True)
valid_links = []
for link in links:
href = link.get('href', '')
text = link.get_text(strip=True)
if (self._is_valid(href, art.url, domain, seen)
and text and 1 < len(text) < 100):
full = urljoin(art.url, href)
if full not in seen:
valid_links.append((text, full))
seen.add(full)
if len(valid_links) >= 3:
sub_articles = []
for text, full in valid_links:
sub_articles.append(Article(text, full, level=art.level + 1))
sub_articles = self._expand_nested(sub_articles, seen, domain, depth + 1)
expanded.extend(sub_articles)
time.sleep(0.15)
except Exception:
pass
return expanded
def _walk_sidebar(self, elem: Tag, arts: List[Article],
seen: Set[str], base: str, domain: str, level: int):
if not elem or level > 6:
return
for child in elem.children:
if not isinstance(child, Tag):
continue
if child.name == 'a':
self._try_add(child, arts, seen, base, domain, level)
elif child.name in ('div', 'ul', 'ol', 'li', 'nav', 'section', 'span', 'dd', 'dl', 'dt'):
has_title = child.find(['h2', 'h3', 'h4', 'h5', 'strong', 'b'],
recursive=False)
self._walk_sidebar(child, arts, seen, base, domain,
level + 1 if has_title else level)
def _extract_links(self, content: Tag, arts: List[Article],
seen: Set[str], base: str, domain: str):
for a in content.find_all('a', href=True):
self._try_add(a, arts, seen, base, domain)
def _try_add(self, a: Tag, arts: List[Article], seen: Set[str],
base: str, domain: str, level: int = 1):
href = a.get('href', '')
if not self._is_valid(href, base, domain, seen):
return
full = urljoin(base, href).rstrip('/')
if full in seen:
return
t = a.get_text(strip=True)
if t and 1 < len(t) < 100:
arts.append(Article(t, full, level=level))
seen.add(full)
def _is_valid(self, href: str, base: str, domain: str, seen: Set[str]) -> bool:
if not href or href.startswith('#') or href.startswith('javascript'):
return False
full = urljoin(base, href).rstrip('/')
if full in seen:
return False
parsed = urlparse(full)
if parsed.netloc and parsed.netloc != domain:
return False
lower = href.lower()
return not any(p in lower for p in self._SKIP)
@staticmethod
def _get_title(soup: BeautifulSoup) -> str:
# 优先从title标签获取
title_tag = soup.find('title')
if title_tag:
t = title_tag.get_text(strip=True)
# 清理菜鸟教程后缀
t = re.sub(r'\s*[-|_–—]?\s*菜鸟教程.*', '', t).strip()
# 如果标题不是URL路径,直接返回
if t and not t.endswith('.html') and not t.endswith('.htm'):
return t
# 从h1标签获取
h1_tag = soup.find('h1')
if h1_tag:
t = h1_tag.get_text(strip=True)
# 清理菜鸟教程后缀
t = re.sub(r'\s*[-|_–—]?\s*菜鸟教程.*', '', t).strip()
# 如果标题不是URL路径,直接返回
if t and not t.endswith('.html') and not t.endswith('.htm'):
return t
# 尝试从content区域获取
content = soup.find('div', id='content') or soup.find('div', class_='article-intro')
if content:
content_h1 = content.find('h1')
if content_h1:
t = content_h1.get_text(strip=True)
# 清理菜鸟教程后缀
t = re.sub(r'\s*[-|_–—]?\s*菜鸟教程.*', '', t).strip()
# 如果标题不是URL路径,直接返回
if t and not t.endswith('.html') and not t.endswith('.htm'):
return t
# 都没有找到,返回默认值
return "未知教程"
def extract_article_content(self, article: Article,
download_images: bool, img_dir: str):
try:
soup = self.fetch_soup(article.url)
content = (soup.find('div', id='content') or
soup.find('div', class_='article-intro') or
soup.find('div', class_='article-body') or
soup.find('article') or
soup.find('div', class_=re.compile(r'content|article', re.I)))
if not content:
article.content = "*内容获取失败*"
article.html_content = "<p><em>内容获取失败</em></p>"
return
self.process_content(content, article, download_images, img_dir)
except Exception as e:
article.content = f"*提取失败: {e}*"
article.html_content = f"<p><em>提取失败: {e}</em></p>"
def _extra_clean(self, content: Tag, article: Article):
for tag in content.find_all(class_=re.compile(
r'example_code_btn|tryit_btn|w3-b|color_h|shareit', re.I)):
tag.decompose()
for tag in content.find_all(class_=re.compile(r'breadcrumb|crumb', re.I)):
tag.decompose()
# ==================== CSDN爬虫 ====================
class CSDNCrawler(BaseCrawler):
"""CSDN爬虫 — 加强反爬、列表页、内容提取"""
_NOISE_CLASSES = re.compile(
r'hljs-button|signin|hide-article-box|blog-tags-box|recommend-box'
r'|recommend-item-box|tool-box|more-toolbox|csdn-side-toolbar'
r'|article-copyright|first-recommend-box|template-box'
r'|blog-content-box|operating|toolbar-advert|article-info-box'
r'|follow-nickName-box|toc-article|side-toolbar|passport-login-tip',
re.I
)
_LIST_PATTERNS = (
r'/column/', r'/category_', r'/article/list/',
r'type=blog', r'\?type=', r'/blog$',
)
def __init__(self):
super().__init__()
self.headers.update({
'Referer': 'https://blog.csdn.net/',
'Cookie': 'dc_session_id=10_' + hashlib.md5(
str(time.time()).encode()).hexdigest(),
})
def is_list_page(self, url: str) -> bool:
if re.match(r'^https?://blog\.csdn\.net/[^/]+/?$', url):
return True
if re.match(r'^https?://i-blog\.csdnimg\.cn', url):
return False
return any(re.search(p, url, re.I) for p in self._LIST_PATTERNS)
def extract_column_articles(self, url: str) -> List[Article]:
articles: List[Article] = []
seen: Set[str] = set()
url = url.rstrip('/')
if '/column/' in url:
api_arts = self._try_column_api(url, seen)
if api_arts:
return api_arts
for page in range(1, 21):
try:
page_url = self._page_url(url, page)
resp = self.fetch(page_url)
if resp.status_code != 200:
break
soup = BeautifulSoup(resp.text, 'html.parser')
batch = self._page_articles(soup, seen)
if not batch:
break
articles.extend(batch)
if not self._has_next(soup, page + 1):
break
time.sleep(0.8)
except Exception:
break
return articles
def _try_column_api(self, url: str, seen: Set[str]) -> List[Article]:
m = re.search(r'/column/details/(\d+)', url)
if not m:
return []
column_id = m.group(1)
articles = []
for page in range(1, 51):
try:
api_url = (f'https://blog.csdn.net/community/home-api/v1/'
f'get-business-list?page={page}&size=20'
f'&businessType=blog&orderby=&no498=false'
f'&year=&month=&username=&columnId={column_id}')
resp = self.fetch(api_url)
data = resp.json()
items = data.get('data', {}).get('list', [])
if not items:
break
for item in items:
href = item.get('url', '')
title = item.get('title', '')
if href and title and href not in seen:
articles.append(Article(title, href))
seen.add(href)
time.sleep(0.5)
except Exception:
break
return articles
def _page_url(self, base: str, page: int) -> str:
if page == 1:
return base
if '/column/' in base: