Repository navigation
Expand file tree
/
Copy pathwxarticle_cli.py
More file actions
503 lines (426 loc) · 17.5 KB
/
Copy pathwxarticle_cli.py
File metadata and controls
503 lines (426 loc) · 17.5 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
#!/usr/bin/env python3
"""
微信公众号文章导出工具
用法: python3 wxarticle_cli.py <url> [--format doc|pdf|markdown]
流程:
1. 调用 wechat-article-to-markdown 抓取文章 (Camoufox 反检测浏览器)
2. 将 Markdown + 图片转为 Doc/PDF/Markdown
3. 输出至 ~/Desktop/new-wechat-article/
"""
import sys
import os
import re
import glob
import shutil
import subprocess
from pathlib import Path
from datetime import datetime
# wechat-article-to-markdown 的固定输出目录
TOOL_OUTPUT_DIR = Path(
os.popen("python3 -c \"import importlib.util; s=importlib.util.find_spec('wechat_article_to_markdown'); print(s.origin)\" 2>/dev/null").read().strip()
).parent / "output" if shutil.which("wechat-article-to-markdown") else None
DEST_DIR = Path.home() / "Desktop" / "new-wechat-article"
def find_tool_output_dir():
"""找到 wechat-article-to-markdown 的输出目录"""
try:
result = subprocess.run(
["python3", "-c",
"from pathlib import Path; import wechat_article_to_markdown as m; print(Path(m.__file__).parent / 'output')"],
capture_output=True, text=True
)
if result.returncode == 0:
return Path(result.stdout.strip())
except Exception:
pass
# fallback: 查找 uv tools 安装路径
home = Path.home()
candidates = sorted(home.glob(".local/share/uv/tools/wechat-article-to-markdown/lib/*/site-packages/output"), reverse=True)
if candidates:
return candidates[0]
return None
def fetch_article(url):
"""调用 wechat-article-to-markdown 抓取文章"""
print("🦊 调用 wechat-article-to-markdown 抓取文章...")
result = subprocess.run(
["wechat-article-to-markdown", url],
capture_output=True, text=True, timeout=120
)
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
if result.returncode != 0:
print("❌ 抓取失败")
sys.exit(1)
# 找到输出目录中最新的文章目录
output_dir = find_tool_output_dir()
if not output_dir or not output_dir.exists():
print(f"❌ 找不到输出目录")
sys.exit(1)
# 找最新的子目录 (排除 debug.html 等文件)
subdirs = [d for d in output_dir.iterdir() if d.is_dir()]
if not subdirs:
print("❌ 输出目录为空,抓取可能失败")
sys.exit(1)
# 按修改时间排序,取最新的
article_dir = max(subdirs, key=lambda d: d.stat().st_mtime)
md_files = list(article_dir.glob("*.md"))
if not md_files:
print(f"❌ 在 {article_dir} 中未找到 Markdown 文件")
sys.exit(1)
return article_dir, md_files[0]
def parse_markdown_meta(md_text):
"""从 Markdown 文件中提取元数据"""
meta = {"title": "", "author": "", "publish_time": ""}
for line in md_text.split("\n")[:20]:
if line.startswith("# "):
meta["title"] = line[2:].strip()
# 格式1: > 公众号: xxx / > 发布时间: xxx
elif line.startswith("> 公众号:"):
meta["author"] = line.split(":", 1)[-1].strip()
elif line.startswith("> 发布时间:"):
meta["publish_time"] = line.split(":", 1)[-1].strip()
# 格式2: - **作者:** xxx
elif line.startswith("- **作者"):
meta["author"] = line.split(":**")[-1].strip() if ":**" in line else line.split(":** ")[-1].strip()
elif line.startswith("- **发布时间"):
meta["publish_time"] = line.split(":**")[-1].strip() if ":**" in line else line.split(":** ")[-1].strip()
return meta
def sanitize_filename(title):
"""清理文件名"""
title = re.sub(r'[\\/:*?"<>|]', '_', title)
return title[:50].strip()
def export_markdown(article_dir, md_file):
"""导出为 Markdown(直接复制)"""
DEST_DIR.mkdir(parents=True, exist_ok=True)
dest = DEST_DIR / article_dir.name
if dest.exists():
shutil.rmtree(dest)
shutil.copytree(article_dir, dest)
md_dest = dest / md_file.name
print(f"✅ Markdown 导出成功: {md_dest}")
return str(md_dest)
def export_html(article_dir, md_file):
"""导出为 HTML(带样式,图片用相对路径)"""
import markdown
md_text = md_file.read_text(encoding="utf-8")
meta = parse_markdown_meta(md_text)
# 跳过元数据区域,只转正文
lines = md_text.split("\n")
body_lines = []
in_meta = True
for line in lines:
if in_meta:
if line.startswith("# ") or line.startswith("> ") or line.startswith("- **") or line.startswith("---") or line.strip() == "":
continue
in_meta = False
body_lines.append(line)
body_md = "\n".join(body_lines)
body_html = markdown.markdown(body_md, extensions=["fenced_code", "tables"])
# 构建完整 HTML 文档
title = meta["title"] or article_dir.name
author = meta["author"]
publish_time = meta["publish_time"]
html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{title}</title>
<style>
body {{ max-width: 720px; margin: 40px auto; padding: 0 20px; font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; line-height: 1.8; color: #333; }}
h1 {{ text-align: center; font-size: 24px; margin-bottom: 8px; }}
.meta {{ text-align: center; color: #999; font-size: 14px; margin-bottom: 30px; }}
h2, h3, h4 {{ margin-top: 28px; }}
img {{ max-width: 100%; height: auto; display: block; margin: 16px auto; border-radius: 4px; }}
blockquote {{ border-left: 3px solid #ddd; padding-left: 16px; color: #666; margin: 16px 0; }}
pre {{ background: #f5f5f5; padding: 16px; border-radius: 4px; overflow-x: auto; }}
code {{ background: #f5f5f5; padding: 2px 6px; border-radius: 3px; font-size: 14px; }}
pre code {{ background: none; padding: 0; }}
a {{ color: #576b95; text-decoration: none; }}
hr {{ border: none; border-top: 1px solid #eee; margin: 30px 0; }}
</style>
</head>
<body>
<h1>{title}</h1>
<div class="meta">{author}{(' · ' + publish_time) if publish_time else ''}</div>
<hr>
{body_html}
</body>
</html>"""
# 保存 HTML + 复制图片
DEST_DIR.mkdir(parents=True, exist_ok=True)
safe_title = sanitize_filename(meta["title"] or article_dir.name)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# 创建子目录放 HTML 和图片
html_dir = DEST_DIR / f"{safe_title}_{timestamp}"
html_dir.mkdir(parents=True, exist_ok=True)
# 复制图片目录
images_src = article_dir / "images"
if images_src.exists():
shutil.copytree(images_src, html_dir / "images")
# 写入 HTML
html_path = html_dir / f"{safe_title}.html"
html_path.write_text(html, encoding="utf-8")
print(f"✅ HTML 导出成功: {html_path}")
return str(html_path)
def export_doc(article_dir, md_file):
"""导出为 Word 文档"""
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
md_text = md_file.read_text(encoding="utf-8")
meta = parse_markdown_meta(md_text)
doc = Document()
# 标题
if meta["title"]:
heading = doc.add_heading(meta["title"], 0)
heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 元信息
if meta["author"] or meta["publish_time"]:
p = doc.add_paragraph()
if meta["author"]:
p.add_run(f"作者: {meta['author']}").bold = True
if meta["publish_time"]:
p.add_run(f"\n发布时间: {meta['publish_time']}")
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.add_paragraph("─" * 40)
# 跳过元数据行,处理正文
lines = md_text.split("\n")
in_meta = True
in_code_block = False
for line in lines:
# 跳过开头的元数据区域 (# Title, > meta lines, ---)
if in_meta:
if line.startswith("# "):
continue # 标题已处理
if line.startswith("> ") or line.startswith("- **") or line.startswith("---") or line.strip() == "":
continue
in_meta = False
# 代码块
if line.startswith("```"):
in_code_block = not in_code_block
if in_code_block:
doc.add_paragraph() # 空行分隔
continue
if in_code_block:
p = doc.add_paragraph(line)
for run in p.runs:
run.font.name = "Courier New"
run.font.size = Pt(9)
continue
# 空行
if line.strip() == "":
continue
# 图片: 
img_match = re.match(r'!\[([^\]]*)\]\(([^)]+)\)', line)
if img_match:
img_path = article_dir / img_match.group(2)
if img_path.exists():
try:
doc.add_picture(str(img_path), width=Inches(5.0))
except Exception as e:
doc.add_paragraph(f"[图片: {img_match.group(2)}]")
else:
doc.add_paragraph(f"[图片: {img_match.group(2)}]")
continue
# 标题
heading_match = re.match(r'^(#{1,6})\s+(.+)', line)
if heading_match:
level = len(heading_match.group(1))
doc.add_heading(heading_match.group(2), level=min(level, 4))
continue
# 引用
if line.startswith("> "):
p = doc.add_paragraph(line[2:])
p.style = "Quote"
continue
# 列表
list_match = re.match(r'^[-*]\s+(.+)', line)
if list_match:
doc.add_paragraph(list_match.group(1), style="List Bullet")
continue
num_match = re.match(r'^\d+\.\s+(.+)', line)
if num_match:
doc.add_paragraph(num_match.group(1), style="List Number")
continue
# 普通段落 - 处理粗体/斜体
p = doc.add_paragraph()
_add_formatted_runs(p, line)
# 保存
DEST_DIR.mkdir(parents=True, exist_ok=True)
safe_title = sanitize_filename(meta["title"] or article_dir.name)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = DEST_DIR / f"{safe_title}_{timestamp}.docx"
doc.save(str(output_path))
print(f"✅ Word 导出成功: {output_path}")
return str(output_path)
def _add_formatted_runs(paragraph, text):
"""解析 Markdown 行内格式并添加 runs"""
# 简单处理 **bold** 和 *italic*
parts = re.split(r'(\*\*[^*]+\*\*|\*[^*]+\*)', text)
for part in parts:
if part.startswith("**") and part.endswith("**"):
run = paragraph.add_run(part[2:-2])
run.bold = True
elif part.startswith("*") and part.endswith("*"):
run = paragraph.add_run(part[1:-1])
run.italic = True
else:
# 处理链接 [text](url) → 只保留 text
cleaned = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', part)
if cleaned:
paragraph.add_run(cleaned)
def export_pdf(article_dir, md_file):
"""导出为 PDF"""
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
from reportlab.lib.enums import TA_CENTER
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from PIL import Image as PILImage
# 注册中文字体
font_name = "Helvetica"
for path in ["/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/STHeiti Light.ttc"]:
if os.path.exists(path):
try:
pdfmetrics.registerFont(TTFont("Chinese", path))
font_name = "Chinese"
break
except Exception:
pass
md_text = md_file.read_text(encoding="utf-8")
meta = parse_markdown_meta(md_text)
# 样式
styles = getSampleStyleSheet()
title_style = ParagraphStyle("CTitle", parent=styles["Heading1"], fontSize=20,
alignment=TA_CENTER, fontName=font_name)
meta_style = ParagraphStyle("CMeta", parent=styles["Normal"], fontSize=10,
textColor="gray", alignment=TA_CENTER, fontName=font_name)
body_style = ParagraphStyle("CBody", parent=styles["Normal"], fontSize=11,
leading=16, spaceAfter=10, fontName=font_name)
heading_style = ParagraphStyle("CHeading", parent=styles["Heading2"], fontSize=14,
spaceAfter=10, fontName=font_name)
code_style = ParagraphStyle("CCode", parent=styles["Normal"], fontSize=9,
fontName="Courier", leading=12, spaceAfter=6,
leftIndent=20, backColor="#f5f5f5")
story = []
# 标题
if meta["title"]:
# XML-escape for reportlab
safe_title = meta["title"].replace("&", "&").replace("<", "<").replace(">", ">")
story.append(Paragraph(safe_title, title_style))
story.append(Spacer(1, 0.2 * inch))
# 元信息
if meta["author"] or meta["publish_time"]:
meta_text = ""
if meta["author"]:
meta_text += f"作者: {meta['author']}"
if meta["publish_time"]:
meta_text += f"<br/>发布时间: {meta['publish_time']}"
story.append(Paragraph(meta_text, meta_style))
story.append(Spacer(1, 0.3 * inch))
# 正文
lines = md_text.split("\n")
in_meta = True
in_code_block = False
for line in lines:
if in_meta:
if line.startswith("# "):
continue
if line.startswith("> ") or line.startswith("- **") or line.startswith("---") or line.strip() == "":
continue
in_meta = False
# 代码块
if line.startswith("```"):
in_code_block = not in_code_block
continue
if in_code_block:
safe_line = line.replace("&", "&").replace("<", "<").replace(">", ">")
story.append(Paragraph(safe_line or " ", code_style))
continue
if line.strip() == "":
story.append(Spacer(1, 0.1 * inch))
continue
# 图片
img_match = re.match(r'!\[([^\]]*)\]\(([^)]+)\)', line)
if img_match:
img_path = article_dir / img_match.group(2)
if img_path.exists():
try:
img = Image(str(img_path), width=5 * inch, height=4 * inch, kind='proportional')
story.append(img)
story.append(Spacer(1, 0.1 * inch))
except Exception:
pass
continue
# 标题
heading_match = re.match(r'^(#{1,6})\s+(.+)', line)
if heading_match:
safe_text = heading_match.group(2).replace("&", "&").replace("<", "<").replace(">", ">")
story.append(Spacer(1, 0.1 * inch))
story.append(Paragraph(safe_text, heading_style))
continue
# 普通文本 (处理 markdown 格式)
safe_line = line.replace("&", "&").replace("<", "<").replace(">", ">")
# **bold** → <b>bold</b>
safe_line = re.sub(r'\*\*([^*]+)\*\*', r'<b>\1</b>', safe_line)
# *italic* → <i>italic</i>
safe_line = re.sub(r'\*([^*]+)\*', r'<i>\1</i>', safe_line)
# [text](url) → text
safe_line = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', safe_line)
# > quote
if safe_line.startswith("> "):
safe_line = f"<i>{safe_line[5:]}</i>"
# list items
safe_line = re.sub(r'^[-*]\s+', '• ', safe_line)
safe_line = re.sub(r'^\d+\.\s+', '', safe_line)
story.append(Paragraph(safe_line, body_style))
# 生成 PDF
DEST_DIR.mkdir(parents=True, exist_ok=True)
safe_title = sanitize_filename(meta["title"] or article_dir.name)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = DEST_DIR / f"{safe_title}_{timestamp}.pdf"
doc = SimpleDocTemplate(str(output_path), pagesize=A4)
doc.build(story)
print(f"✅ PDF 导出成功: {output_path}")
return str(output_path)
def main():
if len(sys.argv) < 2:
print("用法: python3 wxarticle_cli.py <微信文章链接> [--format doc|pdf|html|markdown]")
sys.exit(1)
url = sys.argv[1]
if "mp.weixin.qq.com" not in url:
print("❌ 请输入有效的微信公众号文章链接")
sys.exit(1)
# 解析格式参数
fmt = "pdf" # 默认 PDF
if "--format" in sys.argv:
idx = sys.argv.index("--format")
if idx + 1 < len(sys.argv):
fmt = sys.argv[idx + 1].lower()
if fmt not in ("doc", "pdf", "html", "markdown"):
print(f"❌ 不支持的格式: {fmt},可选: doc, pdf, html, markdown")
sys.exit(1)
# 1. 抓取文章
article_dir, md_file = fetch_article(url)
print(f"📁 文章目录: {article_dir}")
print(f"📄 Markdown: {md_file}")
# 检查图片
images_dir = article_dir / "images"
img_count = len(list(images_dir.glob("*"))) if images_dir.exists() else 0
print(f"🖼 图片数量: {img_count}")
# 2. 导出
if fmt == "markdown":
output = export_markdown(article_dir, md_file)
elif fmt == "doc":
output = export_doc(article_dir, md_file)
elif fmt == "html":
output = export_html(article_dir, md_file)
elif fmt == "pdf":
output = export_pdf(article_dir, md_file)
print(f"\n📁 输出目录: {DEST_DIR}")
return output
if __name__ == "__main__":
main()