全民閱讀的時代已經來臨,目前使用讀書軟件的用戶數2.1億,日活躍用戶超過500萬,其中19-35歲年輕用戶佔比超過60%,本科及以上學歷用戶佔比高達80%,北上廣深及其餘省會城市/直轄市用戶佔比超過80%。本人習慣使用微信讀書,爲了方便整理書籍和導出筆記,便開發了這個小工具。python
首先,咱們先看一下總體目錄結構git
Code ├─ excel_func.py 讀寫excel文件 ├─ pyqt_gui.py PyQt GUI界面 └─ wereader.py 微信讀書相關api
使用xlrd和xlwt庫對excel文件進行讀寫操做github
使用PyQt繪製GUI界面web
經過抓包解析得到相關apijson
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)
該函數的代碼流程爲:api
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() # 初次運行軟件時刪除全部cookies QWebEngineProfile.defaultProfile().cookieStore().cookieAdded.connect(self.onCookieAdd) # cookies增長時觸發self.onCookieAdd()函數 self.browser.loadFinished.connect(self.onLoadFinished) # 網頁加載完畢時觸發self.onLoadFinished()函數 self.browser.load(QUrl(url)) # 加載網頁 self.setCentralWidget(self.browser) # 設置中心窗口
該函數的代碼流程爲:瀏覽器
# 網頁加載完畢事件 def onLoadFinished(self): global USER_VID global HEADERS # 獲取cookies cookies = ['{}={};'.format(key, value) for key,value in self.DomainCookies.items()] cookies = ' '.join(cookies) # 添加Cookie到header HEADERS.update(Cookie=cookies) # 判斷是否成功登陸微信讀書 if login_success(HEADERS): print('登陸微信讀書成功!') # 獲取用戶user_vid if 'wr_vid' in self.DomainCookies.keys(): USER_VID = self.DomainCookies['wr_vid'] print('用戶id:{}'.format(USER_VID)) # 關閉整個qt窗口 self.close() else: print('請掃描二維碼登陸微信讀書...')
該函數的代碼流程爲:bash
# 添加cookies事件 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})
該函數的代碼流程爲:微信
books = get_bookshelf(USER_VID, HEADERS) # 獲取書架上的書籍 books_finish_read = books['finishReadBooks'] books_recent_read = books['recentBooks'] books_all = books['allBooks'] write_excel_xls_append(data_dir + '個人書架.xls', '已讀完的書籍', books_finish_read) # 追加寫入excel文件 write_excel_xls_append(data_dir + '個人書架.xls', '最近閱讀的書籍', books_recent_read) # 追加寫入excel文件 write_excel_xls_append(data_dir + '個人書架.xls', '全部的書籍', books_all) # 追加寫入excel文件 # 獲取書架上的每本書籍的筆記 for index, book in enumerate(books_finish_read): book_id = book[0] book_name = book[1] notes = get_bookmarklist(book[0], HEADERS) with open(note_dir + book_name + '.txt', 'w') as f: f.write(notes) print('導出筆記 {} ({}/{})'.format(note_dir + book_name + '.txt', index+1, len(books_finish_read)))
該函數的代碼流程爲:markdown
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() # 最近閱讀的書籍 books_all = 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)
該函數的代碼流程爲:
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() # clipboard.copy(json.dumps(data, indent=4, sort_keys=True)) 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']): # for item in data['updated']: chapter = item['chapterUid'] text = item['markText'] create_time = item["createTime"] 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 + '\n' for start, text in sorted(contents[c], key=lambda e: e[0]): res += '> ' + text.strip() + '\n\n' res += '\n' return res
該函數的代碼流程爲:
# 跳轉到當前目錄 cd 目錄名 # 先卸載依賴庫 pip uninstall -y -r requirement.txt # 再從新安裝依賴庫 pip install -r requirement.txt -i https://pypi.tuna.tsinghua.edu.cn/simple # 開始運行 python pyqt_gui.py
項目持續更新,歡迎您star本項目