返回 Social Auto Upload
article.py
根目录 / uploader / zhihu_uploader / article.py
1 """知乎文章发布:正文文本、正文图片、定时设置和提交结果记录。"""
2 from __future__ import annotations
3
4 import base64
5 import json
6 import re
7 import sys
8 from datetime import datetime
9 from pathlib import Path
10 from uuid import uuid4
11
12 from patchright.async_api import Page, async_playwright, expect
13
14 from conf import LOCAL_CHROME_PATH
15 from utils.article_render import load_article, ARTICLE_MARKDOWN_EXTENSIONS
16 from uploader.zhihu_uploader.constants import (
17 ZHIHU_ARTICLE_TITLE_MAX, ZHIHU_ARTICLE_URL, ZHIHU_IMAGE_EXTENSIONS, ZHIHU_TIMEZONE,
18 )
19 from uploader.zhihu_uploader.schedule import fill_zhihu_article_schedule, validate_zhihu_schedule
20 from uploader.zhihu_uploader.session import load_zhihu_identity, read_zhihu_identity
21
22
23 class ZhihuArticle:
24 """按原稿结构导入正文,在原稿位置上传图片,核对后只发表一次。"""
25
26 def __init__(self, title, content_file, account_file, schedule=None,
27 headless=True, debug=False, prepare_only=False, upload_timeout=600):
28 self.title = title
29 self.content_file = Path(content_file).expanduser().resolve()
30 self.account_file = Path(account_file).resolve()
31 self.schedule = schedule
32 self.headless = headless
33 self.debug = debug
34 self.prepare_only = prepare_only
35 self.upload_timeout = upload_timeout
36
37 def validate_upload_args(self) -> None:
38 """在启动浏览器前检查标题、正文、图片及定时时间。"""
39 if not self.title.strip() or len(self.title) > ZHIHU_ARTICLE_TITLE_MAX:
40 raise ValueError(f"知乎文章标题需为 1–{ZHIHU_ARTICLE_TITLE_MAX} 字")
41 self.document = load_article(
42 self.content_file, "plain" if self.content_file.suffix.lower() in ARTICLE_MARKDOWN_EXTENSIONS else None,
43 )
44 self.images = self.document.images
45 if not "".join(self.document.text).strip():
46 raise ValueError("知乎文章正文不能为空")
47 if not self.account_file.is_file():
48 raise FileNotFoundError("请先执行 sau zhihu login 保存账号")
49 self.identity = load_zhihu_identity(self.account_file)
50 self.schedule = validate_zhihu_schedule(self.schedule)
51 if self.upload_timeout <= 0:
52 raise ValueError("上传期限必须大于 0 秒")
53 for image in self.images:
54 if not image.is_file():
55 raise FileNotFoundError(f"知乎正文图片不存在: {image}")
56 if image.suffix.lower() not in ZHIHU_IMAGE_EXTENSIONS:
57 raise ValueError(f"知乎文章图片格式不支持: {image.suffix}")
58
59 async def fill_article_form(self, page: Page) -> None:
60 """通过原生粘贴导入富文本;按原稿位置上传图片并核对交错顺序。"""
61 # 标题 placeholder 来自文章表单的实际 textarea,避免误填正文和搜索框。
62 title = page.locator('textarea[placeholder="请输入标题(最多 100 个字)"]')
63 await expect(title).to_have_count(1)
64 body = page.locator('div[contenteditable="true"][role="textbox"]')
65 await expect(body).to_have_count(1)
66 # 知乎编辑器会自动保存;新任务只写空编辑器,避免覆盖账号中恢复出的旧草稿。
67 if ((await title.input_value()).strip() or (await body.inner_text()).strip()
68 or await body.locator("img").count()):
69 raise RuntimeError("知乎文章编辑器已有草稿内容,拒绝覆盖;请先处理该草稿")
70 await title.fill(self.title)
71 await expect(title).to_have_value(self.title)
72 # 不改写 DraftJS innerHTML;原生 HTML 粘贴使编辑器自己更新内部模型。
73 # 图片先替换成唯一标记,避免把本地路径粘贴为无法加载的远端图片。
74 parts, insertions = [], []
75 for part in self.document.parts:
76 if isinstance(part, Path):
77 marker = f"SAU_IMAGE_{uuid4().hex}"
78 parts.append(marker)
79 insertions.append((marker, part))
80 else:
81 parts.append(part)
82 await page.context.grant_permissions(["clipboard-read", "clipboard-write"], origin="https://zhuanlan.zhihu.com")
83 await page.evaluate("""async html => navigator.clipboard.write([
84 new ClipboardItem({'text/html': new Blob([html], {type: 'text/html'})})
85 ])""", "".join(parts))
86 await body.click()
87 await body.press("Meta+V" if sys.platform == "darwin" else "Control+V")
88 await title.click()
89 for marker, _ in insertions:
90 await expect(body).to_contain_text(marker)
91 self.uploaded_images = []
92 for index, (marker, image) in enumerate(insertions, 1):
93 # 文本节点中的唯一标记确定原稿图片位置,不能用点击正文后默认光标位置代替。
94 await body.evaluate("""(body, marker) => {
95 body.focus(); const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
96 let node;
97 while (node = walker.nextNode()) {
98 const offset = node.textContent.indexOf(marker);
99 if (offset < 0) continue;
100 const range = document.createRange(); range.setStart(node, offset);
101 range.setEnd(node, offset + marker.length);
102 const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
103 return;
104 }
105 throw Error('找不到原稿图片位置标记');
106 }""", marker)
107 await body.press("Shift")
108 await body.press("Backspace")
109 await expect(body).not_to_contain_text(marker)
110 # 当前文章编辑器实测支持图片剪贴板粘贴,图片按钮则先打开素材面板。
111 # 在已确认的原稿光标位置粘贴,让 DraftJS 自行创建图片块及发起上传。
112 # 浏览器 ClipboardItem 支持 PNG;其他格式继续使用原生文件 input。
113 if image.suffix.lower() == ".png":
114 await page.evaluate("""async encoded => {
115 const bytes = Uint8Array.from(atob(encoded), c => c.charCodeAt(0));
116 await navigator.clipboard.write([
117 new ClipboardItem({'image/png': new Blob([bytes], {type: 'image/png'})})
118 ]);
119 }""", base64.b64encode(image.read_bytes()).decode("ascii"))
120 await body.press("Meta+V" if sys.platform == "darwin" else "Control+V")
121 else:
122 # accept/multiple 排除封面和文档导入 input,非 PNG 路径仍待真实上传验证。
123 image_input = page.locator('input[type="file"][accept^="image/webp"][multiple]')
124 await expect(image_input).to_have_count(1)
125 await image_input.evaluate("input => { input.value = ''; }")
126 await image_input.set_input_files(str(image))
127 await expect(body.locator("img")).to_have_count(index, timeout=self.upload_timeout * 1000)
128 # 已断言图片数量,按本次逐张插入顺序核对服务器地址和实际解码状态。
129 inserted = body.locator("img").nth(index - 1)
130 await expect(inserted).to_have_attribute("src", re.compile(r"^https://"), timeout=self.upload_timeout * 1000)
131 await expect(inserted).to_have_js_property("complete", True, timeout=self.upload_timeout * 1000)
132 if await inserted.evaluate("image => image.naturalWidth") <= 0:
133 raise RuntimeError(f"知乎文章第 {index} 张图片无法加载")
134 self.uploaded_images.append(await inserted.get_attribute("src"))
135 await title.click()
136 sources = await body.locator("img").evaluate_all("images => images.map(image => image.getAttribute('src'))")
137 if sources != self.uploaded_images:
138 raise RuntimeError("知乎文章图片被重排或替换,停止提交")
139 await self.check_article_body(body)
140
141 await fill_zhihu_article_schedule(page, self.schedule)
142
143 async def check_article_body(self, body) -> None:
144 """核对全部文字、段间图片位置和基本格式,平台过滤或重排时中止提交。"""
145 # 知乎 DraftJS 实测将行内加粗/斜体写为带样式的 span,不能只数 strong/em 标签。
146 actual = await body.evaluate(r"""body => {
147 let sequence = '';
148 function visit(node) {
149 if (node.nodeType === Node.TEXT_NODE) { sequence += node.nodeValue; return; }
150 if (node.nodeName === 'IMG') { sequence += '\x00IMG\x00'; return; }
151 node.childNodes.forEach(visit);
152 }
153 visit(body);
154 return {sequence, formats: Object.fromEntries(
155 ['h1','h2','h3','h4','h5','h6','strong','em','ul','ol','blockquote','pre'].map(
156 tag => [tag, tag === 'strong'
157 ? body.querySelectorAll('strong,b,span[style*="font-weight: bold"],span[style*="font-weight: 700"]').length
158 : tag === 'em' ? body.querySelectorAll('em,i,span[style*="font-style: italic"]').length
159 : body.querySelectorAll(tag).length]
160 )), links: [...body.querySelectorAll('a')].map(a => [a.textContent, a.getAttribute('href')])};
161 }""")
162 normalize = lambda text: re.sub(r"[\s\u200b\ufeff]+", "", text)
163 if normalize(actual["sequence"]) != normalize("".join(self.document.sequence)):
164 raise RuntimeError("知乎文章文字或段间图片位置与原稿不一致,停止提交")
165 for tag, count in actual["formats"].items():
166 if count != self.document.tags[tag]:
167 raise RuntimeError(f"知乎文章格式不一致: {tag} 期望 {self.document.tags[tag]},实际 {count}")
168 expected_links = await body.page.evaluate("""html => {
169 const template = document.createElement('template'); template.innerHTML = html;
170 return [...template.content.querySelectorAll('a')].map(a => [a.textContent, a.getAttribute('href')]);
171 }""", self.document.content_html)
172 if [[normalize(text), href] for text, href in actual["links"]] != [[normalize(text), href] for text, href in expected_links]:
173 raise RuntimeError("知乎文章链接文字或目标与原稿不一致")
174
175 async def main(self) -> dict:
176 """仅以作品详情 URL 作为已发表证据;提交响应未知时禁止自动重试。"""
177 self.validate_upload_args()
178 results_dir = self.account_file.parent / "zhihu_results"
179 results_dir.mkdir(exist_ok=True)
180 result_file = results_dir / f"{datetime.now(ZHIHU_TIMEZONE):%Y%m%d-%H%M%S}-{uuid4().hex[:8]}.json"
181 result = {
182 "success": False, "status": "preparing", "type": "article", "title": self.title,
183 "content_file": str(self.content_file), "images": [str(image) for image in self.images],
184 "identity": self.identity, "result_file": str(result_file),
185 }
186 if self.schedule:
187 result["schedule"] = self.schedule.isoformat()
188 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
189
190 async with async_playwright() as playwright:
191 browser = await playwright.chromium.launch(
192 executable_path=LOCAL_CHROME_PATH or None, channel="chrome", headless=self.headless,
193 )
194 page = None
195 submitted = False
196 try:
197 context = await browser.new_context(
198 storage_state=str(self.account_file), timezone_id="Asia/Shanghai",
199 )
200 page = await context.new_page()
201 response = await page.goto(ZHIHU_ARTICLE_URL, wait_until="domcontentloaded", timeout=45000)
202 if response is not None and response.status >= 400:
203 raise RuntimeError(f"知乎文章编辑器访问失败,HTTP {response.status}")
204 if await read_zhihu_identity(page) != self.identity:
205 raise RuntimeError("知乎文章编辑器页头与本地账号绑定不一致")
206 await self.fill_article_form(page)
207 result.update(images=self.uploaded_images, manifest=self.document.manifest)
208 result["status"] = "prepared"
209 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
210 if self.prepare_only:
211 return result
212
213 # 发布按钮只有标题和正文满足编辑器要求后才可用;提交只触发一次。
214 publish = page.get_by_role("button", name="发布", exact=True)
215 await expect(publish).to_be_enabled()
216 submitted = True
217 result["status"] = "submission_unknown"
218 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
219 await publish.click()
220 # 草稿也有 /p/<id>/edit 地址;必须到正式详情页并读到作品标题才算发表。
221 await page.wait_for_url(re.compile(r"^https://zhuanlan\.zhihu\.com/p/\d+/?(?:\?.*)?$"), timeout=60000)
222 await expect(page.get_by_role("article").get_by_role("heading", name=self.title, exact=True)).to_be_visible()
223 result.update(success=True, status="published", url=page.url)
224 return result
225 except Exception as exc:
226 result["error"] = str(exc)
227 if submitted:
228 result["status"] = "submission_unknown"
229 if page is not None and re.fullmatch(r"https://zhuanlan\.zhihu\.com/p/\d+/?(?:\?.*)?", page.url):
230 result["url"] = page.url
231 else:
232 result["status"] = "failed_before_submit"
233 if self.debug and page is not None:
234 screenshot = result_file.with_suffix(".png")
235 await page.screenshot(path=str(screenshot))
236 result["screenshot"] = str(screenshot)
237 raise RuntimeError(f"知乎文章阶段={result['status']},结果文件={result_file}: {exc}") from exc
238 finally:
239 result_file.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
240 await browser.close()
241
241 lines PYTHON