WeChat Reading Assistant: Python Tool for Exporting Books and Notes
This guide introduces a Python-based WeChat Reading Assistant that uses PyQt for a GUI, extracts bookshelf data via WeChat APIs, and writes book information and notes to Excel files, providing step‑by‑step code explanations and usage instructions for developers.
The author created a small utility to organize WeChat Reading books and export notes, using Python with xlrd/xlwt for Excel handling and PyQt for a graphical interface.
Directory structure :
├─ excel_func.py 读写excel文件
├─ pyqt_gui.py PyQt GUI界面
└─ wereader.py 微信读书相关apiexcel_func.py provides write_excel_xls to create a workbook, add sheets, write data, and save the file:
def write_excel_xls(path, sheet_name_list, value):
# 新建一个工作簿
workbook = xlwt.Workbook()
index = len(value)
for sheet_name in sheet_name_list:
sheet = workbook.add_sheet(sheet_name)
for i in range(0, index):
for j in range(0, len(value[i])):
sheet.write(i, j, value[i][j])
workbook.save(path)pyqt_gui.py defines a MainWindow class that launches a QWebEngineView to load the WeChat Reading login page, captures cookies, and triggers data export after successful login:
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.DomainCookies = {}
self.setWindowTitle('微信读书助手')
self.resize(900, 600)
self.setWindowFlags(Qt.WindowMinimizeButtonHint)
self.setFixedSize(self.width(), self.height())
url = 'https://weread.qq.com/#login'
self.browser = QWebEngineView()
QWebEngineProfile.defaultProfile().cookieStore().deleteAllCookies()
QWebEngineProfile.defaultProfile().cookieStore().cookieAdded.connect(self.onCookieAdd)
self.browser.loadFinished.connect(self.onLoadFinished)
self.browser.load(QUrl(url))
self.setCentralWidget(self.browser)
def onLoadFinished(self):
global USER_VID, HEADERS
cookies = ['{}={};'.format(k, v) for k, v in self.DomainCookies.items()]
HEADERS.update(Cookie=' '.join(cookies))
if login_success(HEADERS):
if 'wr_vid' in self.DomainCookies:
USER_VID = self.DomainCookies['wr_vid']
print(f'用户id:{USER_VID}')
self.close()
else:
print('请扫描二维码登录微信读书...')
def onCookieAdd(self, cookie):
if 'weread.qq.com' in cookie.domain():
name = cookie.name().data().decode('utf-8')
value = cookie.value().data().decode('utf-8')
if name not in self.DomainCookies:
self.DomainCookies.update({name: value})wereader.py contains API helpers. get_bookshelf fetches recent, finished, and all books, filtering out public accounts, and returns a dictionary of Book objects:
def get_bookshelf(userVid, headers):
"""获取书架上所有书"""
url = "https://i.weread.qq.com/shelf/friendCommon"
params = dict(userVid=userVid)
r = requests.get(url, params=params, headers=headers, verify=False)
if not r.ok:
raise Exception(r.text)
data = r.json()
books_finish_read = set()
books_recent_read = set()
for book in data['recentBooks']:
if not book['bookId'].isdigit():
continue
b = Book(book['bookId'], book['title'], book['author'], book['cover'], book['intro'], book['category'])
books_recent_read.add(b)
books_all = books_finish_read + books_recent_read
return dict(finishReadBooks=books_finish_read, recentBooks=books_recent_read, allBooks=books_all) get_bookmarklistretrieves a book's notes, organizes them by chapter, and formats the output as markdown:
def get_bookmarklist(bookId, headers):
"""获取某本书的笔记返回md文本"""
url = "https://i.weread.qq.com/book/bookmarklist"
params = dict(bookId=bookId)
r = requests.get(url, params=params, headers=headers, verify=False)
if not r.ok:
raise Exception(r.text)
data = r.json()
chapters = {c['chapterUid']: c['title'] for c in data['chapters']}
contents = defaultdict(list)
for item in sorted(data['updated'], key=lambda x: x['chapterUid']):
chapter = item['chapterUid']
text = item['markText']
start = int(item['range'].split('-')[0])
contents[chapter].append((start, text))
res = ''
for c in sorted(chapters.keys()):
title = chapters[c]
res += '#'*chapters_map[title] + ' ' + title + '
'
for start, text in sorted(contents[c], key=lambda e: e[0]):
res += '> ' + text.strip() + '
'
res += '
'
return resRunning the tool :
# Jump to the project directory
cd <directory_name>
# Uninstall existing dependencies
pip uninstall -y -r requirement.txt
# Re‑install dependencies from Tsinghua mirror
pip install -r requirement.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# Launch the GUI
python pyqt_gui.pyAfter successful login, the script writes finished, recent, and all books to 我的书架.xls and saves each book's notes as separate .txt files.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
