Repository navigation
Expand file tree
/
Copy pathexport.py
More file actions
321 lines (277 loc) · 17.1 KB
/
Copy pathexport.py
File metadata and controls
321 lines (277 loc) · 17.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
#!/usr/bin/env python3
"""把微信公众号的历史文章导出成 Markdown 和 CSV。不用扫码,不用公众号后台,不用 Cookie。
python3 export.py 36氪 --pages 1 --limit 5 --full-text # 只算钱,不调用
python3 export.py 36氪 --pages 1 --limit 5 --full-text --yes # 真跑
Python 3.9+,只用标准库。Key 放在环境变量 DATAXAPI_API_KEY,或复制 .env.example 成 .env 填进去。
In English: add --lang en (README.en.md).
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import re
import sys
import time
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
API = "https://api.dataxapi.com/v1/"
SOURCE = "gh-wechat-article-export"
LANG = "zh" # --lang en 时是 "en"
PRICE = Decimal("0.02") # 这四个接口都是每次 $0.02,现价见 https://dataxapi.com/prices.json
DEFAULT_PER_PAGE = 20 # 没给 --limit 时,每页算 20 篇封顶,这样“最多花多少”是真的
CHINA = timezone(timedelta(hours=8))
NO_TEXT = "没有文字" # 付费取过了,文章本身没有文字(比如只有图片),重跑也不再取
GONE = "已删除" # 接口确认文章已经没有了,这次也收费,重跑也不再取
STATS = {"阅读": "views", "点赞": "likes", "分享": "shares", "收藏": "favorites", "评论数": "comments"}
STATS_AT = "数据时间"
COLUMNS = ["发布时间", "标题", "链接", "摘要", "全文", "文件", "编号"]
# 程序里一直用中文列名和状态,只在读写 index.csv 时换成英文。换语言重跑,取过的照样认得,不会再花钱。
ENGLISH_COLUMNS = {
"发布时间": "Published (Beijing time)", "标题": "Title", "链接": "URL", "摘要": "Summary", "全文": "Full text", "文件": "File", "编号": "ID",
"阅读": "Reads", "点赞": "Likes", "分享": "Shares", "收藏": "Saves", "评论数": "Comments", STATS_AT: "Counted at (Beijing time)",
}
ENGLISH_STATES = {"有": "yes", "无": "no", NO_TEXT: "no text", GONE: "deleted"}
OVER_100K = ("10万+", "100000+")
NOT_FOUND = (" 查不到", " not found")
def say(chinese: str, english: str) -> str:
return english if LANG == "en" else chinese
def source() -> str:
return SOURCE + say("", "-en")
class ApiError(Exception):
def __init__(self, message: str, gone: bool = False):
super().__init__(message)
self.gone = gone # 查到了“没有这篇文章”,再查一次还是这样
class Api:
def __init__(self, key: str):
self.key, self.calls, self.failed, self.charged = key, 0, 0, Decimal(0)
def call(self, capability: str, **params) -> dict:
request = Request(
API + capability.replace(".", "/") + "?" + urlencode(params),
headers={"Authorization": f"Bearer {self.key}", "X-Source": source(), "User-Agent": source()},
)
for last in (False, True):
self.calls += 1
try:
with urlopen(request, timeout=120) as response:
body = json.load(response)
self.charged += Decimal(str(body.get("meta", {}).get("billing", {}).get("amount") or 0))
return body
except HTTPError as error:
self.failed += 1
if not last and error.code in (429, 500, 502, 503, 504):
time.sleep(3) # 没扣费,重试一次
continue
try:
answer = json.load(error)
except ValueError:
answer = {}
if answer.get("charged"):
self.charged += Decimal(str(answer.get("amount") or 0))
raise ApiError(answer.get(say("message_zh", "message")) or f"HTTP {error.code}", answer.get("code") == "not_found") from error
except OSError as error:
self.failed += 1
raise ApiError(say("连不上接口:", "could not reach the API: ") + str(error)) from error
raise AssertionError
def load_env(path: Path) -> None:
"""读脚本旁边的 .env(KEY=VALUE 一行一个),已经设了的环境变量优先。"""
if not path.exists():
return
for line in path.read_text(encoding="utf-8").splitlines():
name, sep, value = line.strip().partition("=")
if sep and name and not name.startswith("#"):
os.environ.setdefault(name.strip(), value.strip().strip('"').strip("'"))
def resolve(api: Api, account: str) -> tuple[str, str]:
"""公众号名字换成原始编号。名字不完全一样时不猜,免得导出错的号。"""
if account.startswith("gh_"):
return account, account
items = api.call("wechat.accounts.search", query=account)["data"]["items"]
for item in items:
if item.get("name") == account:
return item["id"], account
near = say("、", ", ").join(say(f"{i.get('name')}({i.get('id')})", f"{i.get('name')} ({i.get('id')})") for i in items[:5]) or say("没有", "none")
raise ApiError(say(f"没有名字完全是“{account}”的公众号。相近的:{near}。换成准确的名字或 gh_ 编号再跑",
f'no account is named exactly "{account}". Close ones: {near}. Run again with the exact name or the gh_ ID'))
def china_time(value: str | None) -> str:
if not value:
return ""
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(CHINA).strftime("%Y-%m-%d %H:%M")
def file_name(title: str | None, published: str, taken: set[str]) -> str:
untitled, day = say("无标题", "untitled"), published[:10] or say("无日期", "no-date")
safe = re.sub(r'[\\/:*?"<>|\s]+', " ", title or untitled).strip()[:60] or untitled
name, n = f"{day}_{safe}.md", 1
while name in taken:
n += 1
name = f"{day}_{safe}_{n}.md"
taken.add(name)
return name
def markdown(item: dict, account: str, body: str | None) -> str:
return "\n".join([
f"# {item.get('title') or say('无标题', 'untitled')}",
"",
say("- 公众号:", "- Account: ") + account,
say(f"- 发布时间:{china_time(item.get('published_at'))}(北京时间)", f"- Published: {china_time(item.get('published_at'))} (Beijing time)"),
say("- 原文链接:", "- Original: ") + (item.get("url") or ""),
"",
"---",
"",
body or item.get("text") or "",
"",
say("> 仅供个人研究和资料整理;转载或商用请取得原作者授权。", "> For personal research and reference. Ask the author before republishing it or using it commercially."),
"",
])
def read_index(index: Path) -> dict[str, dict]:
if not index.exists():
return {}
with index.open(encoding="utf-8-sig", newline="") as saved:
rows = list(csv.DictReader(saved))
if rows and ENGLISH_COLUMNS["编号"] in rows[0]:
names, states = ({english: chinese for chinese, english in each.items()} for each in (ENGLISH_COLUMNS, ENGLISH_STATES))
rows = [{names.get(name, name): value for name, value in row.items()} for row in rows]
for row in rows:
row["全文"] = states.get(row["全文"], row["全文"])
for column, (chinese, english) in (("阅读", OVER_100K), (STATS_AT, NOT_FOUND)):
if row.get(column):
row[column] = row[column].replace(english, chinese)
return {row["编号"]: row for row in rows}
def in_english(row: dict) -> dict:
row = {**row, "全文": ENGLISH_STATES.get(row["全文"], row["全文"])}
for column, (chinese, english) in (("阅读", OVER_100K), (STATS_AT, NOT_FOUND)):
if row.get(column):
row[column] = row[column].replace(chinese, english)
return {ENGLISH_COLUMNS.get(name, name): value for name, value in row.items()}
def save_index(index: Path, rows: dict[str, dict]) -> None:
"""先写临时文件再换上去,写到一半断了也不会弄坏原来的目录。"""
draft = index.with_name(index.name + ".tmp")
with draft.open("w", encoding="utf-8-sig", newline="") as saved: # 带 BOM,Excel 打开中文不乱码
# 没取过数据的目录,列和以前一样。
extra = [*STATS, STATS_AT] if any(row.get(STATS_AT) for row in rows.values()) else []
columns, lines = COLUMNS + extra, sorted(rows.values(), key=lambda row: row["发布时间"], reverse=True)
if LANG == "en":
columns, lines = [ENGLISH_COLUMNS[name] for name in columns], [in_english(row) for row in lines]
writer = csv.DictWriter(saved, columns, restval="", extrasaction="ignore")
writer.writeheader()
writer.writerows(lines)
os.replace(draft, index)
def read_stats(api: Api, url: str) -> dict[str, str]:
"""取这一刻的阅读、点赞等。平台没给的留空,不写成 0。"""
now = datetime.now(CHINA).strftime("%Y-%m-%d %H:%M")
try:
item = api.call("wechat_mp.articles.metrics", url=url)["data"]["item"]
except ApiError as error:
if not error.gone:
raise
return {**dict.fromkeys(STATS, ""), STATS_AT: now + NOT_FOUND[0]}
counts = item.get("metrics") or {}
stats = {name: "" if counts.get(field) is None else str(counts[field]) for name, field in STATS.items()}
if any(a.get("field") == "metrics.views" and a.get("kind") == "lower_bound" for a in item.get("approximate") or []):
stats["阅读"] = OVER_100K[0] # 超过 10 万,平台只给“10万+”
return {**stats, STATS_AT: now}
def export(api: Api, account: str, pages: int, limit: int, full_text: bool, out: Path, stats: bool = False) -> None:
account_id, name = resolve(api, account)
folder = out / re.sub(r'[\\/:*?"<>|\s]+', "_", name)
folder.mkdir(parents=True, exist_ok=True)
index = folder / "index.csv"
rows = read_index(index)
taken = {row["文件"] for row in rows.values()}
cursor, fresh, kept = None, 0, 0
for _ in range(pages):
params = {"id": account_id, **({"cursor": cursor} if cursor else {})}
try:
answer = api.call("wechat_mp.accounts.articles.list", **params)
except ApiError as error:
print(say(f" 第 {_ + 1} 页没取到:{error}(已取到的照常保存)", f" Page {_ + 1} was not fetched: {error} (what was fetched before it is kept)"), file=sys.stderr)
break
for item in answer["data"]["items"]:
if fresh + kept >= limit:
break
# 同一篇文章每次返回的链接可能不同,认文章编号。
mark = str(item.get("id") or item.get("url"))
old = rows.get(mark)
state = old["全文"] if old else "无"
# 重跑不重复花钱:全文和数据各看各的,取过的不再取。没有文字的、已删除的也算取过。
want_text = full_text and bool(item.get("url")) and state not in ("有", NO_TEXT, GONE)
want_stats = stats and bool(item.get("url")) and state != GONE and not (old or {}).get(STATS_AT)
if old and not want_text and not want_stats:
kept += 1
continue
published = china_time(item.get("published_at"))
if not old or want_text:
body = None
if want_text:
try:
body = api.call("wechat_mp.articles.get", url=item["url"])["data"]["item"].get("text")
state = "有" if body else NO_TEXT
except ApiError as error:
state = GONE if error.gone else state
want_stats = want_stats and not error.gone
print(say(f" 《{item.get('title')}》没取到全文,先存摘要:{error}", f' No full text for "{item.get("title")}", its summary is saved: {error}'), file=sys.stderr)
target = old["文件"] if old else file_name(item.get("title"), published, taken)
(folder / target).write_text(markdown(item, name, body), encoding="utf-8")
rows[mark] = {**(old or {}), "发布时间": published, "标题": item.get("title") or "", "链接": item.get("url") or "", "摘要": item.get("text") or "", "全文": state, "文件": target, "编号": mark}
save_index(index, rows) # 每取到一样就记一次,中途断了,记下的重跑不再取
if want_stats:
try:
rows[mark].update(read_stats(api, item["url"]))
save_index(index, rows)
except ApiError as error:
print(say(f" 《{item.get('title')}》没取到阅读数据:{error}", f' No counts for "{item.get("title")}": {error}'), file=sys.stderr)
fresh += 1
page = answer.get("page") or {}
cursor = page.get("next_cursor")
if fresh + kept >= limit or not page.get("has_more") or not cursor:
break
save_index(index, rows)
label = name if name == account_id else say(f"{name}({account_id})", f"{name} ({account_id})")
print(say(f"{label}:新存或补全 {fresh} 篇,已有不重取 {kept} 篇 → {folder}/", f"{label}: {fresh} saved or completed, {kept} already there and not fetched again -> {folder}/"))
def main() -> int:
global LANG
language = argparse.ArgumentParser(add_help=False)
language.add_argument("--lang", choices=("zh", "en"), default="zh", help="输出用中文还是英文 / language of the output (zh, en; default zh)")
LANG = language.parse_known_args()[0].lang
parser = argparse.ArgumentParser(parents=[language], description=say("把微信公众号的历史文章导出成 Markdown 和 CSV", "Export a WeChat Official Account's past articles to Markdown and CSV"))
parser.add_argument("accounts", nargs="+", help=say("公众号名字或 gh_ 编号,可以给多个", "exact account names or gh_ IDs, one or more"))
parser.add_argument("--pages", type=int, default=1, help=say("每个号最多翻几页,从最新的开始(默认 1)", "most pages of the list to read per account, newest first (default 1)"))
parser.add_argument("--limit", type=int, help=say("每个号最多导出几篇(默认 页数 × 20)", "most articles to export per account (default: pages x 20)"))
parser.add_argument("--full-text", action="store_true", help=say("每篇多调一次取全文;不加只有摘要", "one more call per article for its full text; without it, summaries only"))
parser.add_argument("--stats", action="store_true", help=say("每篇多调一次,取阅读、点赞、分享、收藏、评论数", "one more call per article for its reads, likes, shares, saves and comment count"))
parser.add_argument("--out", type=Path, default=Path("export"), help=say("导出目录(默认 export)", "folder to export to (default: export)"))
parser.add_argument("--yes", action="store_true", help=say("确认花费,真正运行", "accept the cost and run"))
args = parser.parse_args()
if args.pages < 1 or (args.limit is not None and args.limit < 1):
parser.error(say("--pages 和 --limit 至少是 1", "--pages and --limit must be at least 1"))
articles = args.limit or args.pages * DEFAULT_PER_PAGE
lookups = sum(not a.startswith("gh_") for a in args.accounts)
most = PRICE * (lookups + len(args.accounts) * (args.pages + articles * (args.full_text + args.stats)))
print(say(
f"最多花 ${most:.2f}:{len(args.accounts)} 个号,每个最多 {args.pages} 页"
+ (f"、{articles} 篇全文" if args.full_text else "") + (f"、{articles} 篇的阅读数据" if args.stats else "")
+ f",每次调用 ${PRICE};没查成不扣费",
f"At most ${most:.2f}: accounts {len(args.accounts)}; for each, list pages up to {args.pages}"
+ (f", full texts up to {articles}" if args.full_text else "") + (f", counts for up to {articles}" if args.stats else "")
+ f". ${PRICE} a call. A call that could not be completed is free.",
))
if not args.yes:
print(say("这次没有调用任何接口。确认后加 --yes 再跑。", "Nothing was called. To run it, add --yes."))
return 0
load_env(Path(__file__).with_name(".env"))
key = os.environ.get("DATAXAPI_API_KEY")
if not key:
sign_up = f"https://dataxapi.com/{say('zh/', '')}signin/?ref={source()}"
print(say(f"缺 DATAXAPI_API_KEY。到这里注册领 Key,可免费试用:{sign_up}", f"DATAXAPI_API_KEY is missing. Sign up for a key here (free to try): {sign_up}"), file=sys.stderr)
return 2
api, failed = Api(key), False
for account in args.accounts:
try:
export(api, account, args.pages, articles, args.full_text, args.out, args.stats)
except ApiError as error:
print(f"{account}{say(':', ': ')}{error}", file=sys.stderr)
failed = True
print(say(f"调用 {api.calls} 次,其中没取到 {api.failed} 次,实际扣费 ${api.charged:.4f}", f"Calls: {api.calls}, of which not answered with data: {api.failed}. Charged: ${api.charged:.4f}"))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())