WeRead Assistant: A Python Tool for Exporting Books and Notes from WeChat Read

This article introduces a Python-based WeRead assistant that uses xlrd/xlwt for Excel handling, PyQt for a GUI, and WeChat Read APIs to fetch bookshelf data and export notes, providing step‑by‑step code explanations and usage instructions for developers.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
WeRead Assistant: A Python Tool for Exporting Books and Notes from WeChat Read

The era of mass reading has arrived, with 210 million users of reading apps and over 5 million daily active users; the majority are young, well‑educated users in major Chinese cities.

To organize books and export notes from WeChat Read, the author created a small utility written in Python.

1. Directory Structure

The project consists of three main files:

├─ excel_func.py      # read/write Excel files
├─ pyqt_gui.py       # PyQt GUI interface
└─ wereader.py       # WeChat Read API interactions

2. excel_func.py

This module uses xlrd and xlwt to read and write Excel workbooks. The key function write_excel_xls creates a workbook, adds sheets, writes data row by row, and saves 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)

The workflow is: create Excel file → create sheets → write data → save.

3. pyqt_gui.py

This script builds a PyQt window that embeds a QWebEngineView to load the WeChat Read login page, captures cookies, and triggers login verification.

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):
            print('登录微信读书成功!')
            if 'wr_vid' in self.DomainCookies:
                USER_VID = self.DomainCookies['wr_vid']
                print('用户id:{}'.format(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})

The flow: create Qt window → instantiate QWebEngineView → bind cookie and load‑finished events → load login page → handle cookies → verify login.

4. wereader.py

Provides API wrappers:

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 r.ok:
        data = r.json()
    else:
        raise Exception(r.text)
    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)

And a function to fetch and format notes 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 r.ok:
        data = r.json()
    else:
        raise Exception(r.text)
    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))
    chapters_map = {title: level for level, title in get_chapters(int(bookId), headers)}
    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 res

The workflow: retrieve recent, finished, and all books → filter out public accounts → return a dictionary; then fetch notes, map them to chapters, and output markdown.

5. How to Run

Execute the following commands in the project directory:

# Change to the project directory
cd <directory_name>
# Uninstall existing dependencies
pip uninstall -y -r requirement.txt
# Reinstall dependencies from Tsinghua mirror
pip install -r requirement.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# Launch the GUI
python pyqt_gui.py

After scanning the QR code and successful login, the tool exports the bookshelf to an Excel file and saves each book's notes as individual text files.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

APIExcelPyQtWeChat Read
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.