Python 一键导出微信阅读记录和笔记,


 

全民阅读的时代已经来临,目前使用读书软件的用户数2.1亿,日活跃用户超过500万,其中19-35岁年轻用户占比超过60%,本科及以上学历用户占比高达80%,北上广深及其他省会城市/直辖市用户占比超过80%。

本人习惯使用微信读书,为了方便整理书籍和导出笔记,便开发了这个小工具。

部分截图

代码思路

1. 目录结构

首先,我们先看一下整体目录结构

  1. ├─ excel_func.py                   读写excel文件  
  2. ├─ pyqt_gui.py                     PyQt GUI界面  
  3. └─ wereader.py                     微信读书相关api 
  •  excel_func.py

  使用xlrd和xlwt库对excel文件进行读写操作

  •  pyqt_gui.py

  使用PyQt绘制GUI界面

  •  wereader.py

  通过抓包解析获得相关api

2. excel_func.py

  1. def write_excel_xls(path, sheet_name_list, value):  
  2.     # 新建一个工作簿  
  3.     workbook = xlwt.Workbook()  
  4.     # 获取需要写入数据的行数  
  5.     index = len(value)  
  6.     for sheet_name in sheet_name_list:  
  7.         # 在工作簿中新建一个表格  
  8.         sheet = workbook.add_sheet(sheet_name)  
  9.         # 往这个工作簿的表格中写入数据  
  10.         for i in range(0, index):  
  11.             for j in range(0, len(value[i])):  
  12.                 sheet.write(i, j, value[i][j])  
  13.     # 保存工作簿  
  14.     workbook.save(path) 

该函数的代码流程为:

3. pyqt_gui.py

  1. class MainWindow(QMainWindow):  
  2.     def __init__(self, *args, **kwargs):  
  3.         super().__init__(*args, **kwargs)  
  4.         self.DomainCookies = {}  
  5.         self.setWindowTitle('微信读书助手') # 设置窗口标题  
  6.         self.resize(900, 600) # 设置窗口大小  
  7.         self.setWindowFlags(Qt.WindowMinimizeButtonHint) # 禁止最大化按钮  
  8.         self.setFixedSize(self.width(), self.height()) # 禁止调整窗口大小  
  9.         url = 'https://weread.qq.com/#login' # 目标地址  
  10.         self.browser = QWebEngineView() # 实例化浏览器对象  
  11.         QWebEngineProfile.defaultProfile().cookieStore().deleteAllCookies() # 初次运行软件时删除所有cookies  
  12.         QWebEngineProfile.defaultProfile().cookieStore().cookieAdded.connect(self.onCookieAdd) # cookies增加时触发self.onCookieAdd()函数  
  13.         self.browser.loadFinished.connect(self.onLoadFinished) # 网页加载完毕时触发self.onLoadFinished()函数  
  14.         self.browser.load(QUrl(url)) # 加载网页  
  15.         self.setCentralWidget(self.browser) # 设置中心窗口 

该函数的代码流程为:

  1. # 网页加载完毕事件  
  2.     def onLoadFinished(self):  
  3.         global USER_VID  
  4.         global HEADERS 
  5.         # 获取cookies  
  6.         cookies = ['{}={};'.format(key, value) for key,value in self.DomainCookies.items()]  
  7.         cookies = ' '.join(cookies)  
  8.         # 添加Cookie到header  
  9.         HEADERS.update(Cookie=cookies)  
  10.         # 判断是否成功登录微信读书  
  11.         if login_success(HEADERS):  
  12.             print('登录微信读书成功!')  
  13.             # 获取用户user_vid  
  14.             if 'wr_vid' in self.DomainCookies.keys():  
  15.                 USER_VID = self.DomainCookies['wr_vid']  
  16.                 print('用户id:{}'.format(USER_VID))  
  17.                 # 关闭整个qt窗口  
  18.                 self.close()  
  19.         else:  
  20.             print('请扫描二维码登录微信读书...') 

该函数的代码流程为:

  1. # 添加cookies事件  
  2.    def onCookieAdd(self, cookie):  
  3.        if 'weread.qq.com' in cookie.domain():  
  4.            name = cookie.name().data().decode('utf-8')  
  5.            value = cookie.value().data().decode('utf-8')  
  6.            if name not in self.DomainCookies:  
  7.                self.DomainCookies.update({name: value}) 

该函数的代码流程为:

  1. books = get_bookshelf(USER_VID, HEADERS) # 获取书架上的书籍  
  2.   booksbooks_finish_read = books['finishReadBooks']  
  3.   booksbooks_recent_read = books['recentBooks']  
  4.   booksbooks_all = books['allBooks']  
  5.   write_excel_xls_append(data_dir + '我的书架.xls', '已读完的书籍', books_finish_read) # 追加写入excel文件  
  6.   write_excel_xls_append(data_dir + '我的书架.xls', '最近阅读的书籍', books_recent_read)  # 追加写入excel文件  
  7.   write_excel_xls_append(data_dir + '我的书架.xls', '所有的书籍', books_all)  # 追加写入excel文件  
  8.   # 获取书架上的每本书籍的笔记  
  9.   for index, book in enumerate(books_finish_read):  
  10.       bookbook_id = book[0]  
  11.       bookbook_name = book[1]  
  12.       notes = get_bookmarklist(book[0], HEADERS)  
  13.       with open(note_dir + book_name + '.txt', 'w') as f:  
  14.           f.write(notes)  
  15.       print('导出笔记 {} ({}/{})'.format(note_dir + book_name + '.txt', index+1, len(books_finish_read))) 

该函数的代码流程为:

4. wereader.py

  1. def get_bookshelf(userVid, headers):  
  2.     """获取书架上所有书"""  
  3.     url = "https://i.weread.qq.com/shelf/friendCommon"  
  4.     params = dict(userViduserVid=userVid)  
  5.     r = requests.get(url, paramsparams=params, headersheaders=headers, verify=False)  
  6.     if r.ok:  
  7.         data = r.json()  
  8.     else:  
  9.         raise Exception(r.text)  
  10.     books_finish_read = set() # 已读完的书籍  
  11.     books_recent_read = set() # 最近阅读的书籍  
  12.     books_all = set() # 书架上的所有书籍  
  13.     for book in data['recentBooks']:  
  14.         if not book['bookId'].isdigit(): # 过滤公众号  
  15.             continue  
  16.         b = Book(book['bookId'], book['title'], book['author'], book['cover'], book['intro'], book['category'])  
  17.         books_recent_read.add(b)  
  18.     books_all = books_finish_read + books_recent_read  
  19.     return dict(finishReadBooks=books_finish_read, recentBooks=books_recent_read, allBooks=books_all) 

该函数的代码流程为:

  1. def get_bookmarklist(bookId, headers):  
  2.     """获取某本书的笔记返回md文本"""  
  3.     url = "https://i.weread.qq.com/book/bookmarklist"  
  4.     params = dict(bookIdbookId=bookId)  
  5.     r = requests.get(url, paramsparams=params, headersheaders=headers, verify=False)  
  6.     if r.ok:  
  7.         data = r.json()  
  8.         # clipboard.copy(json.dumps(data, indent=4, sort_keys=True))  
  9.     else:  
  10.         raise Exception(r.text)  
  11.     chapters = {c['chapterUid']: c['title'] for c in data['chapters']}  
  12.     contents = defaultdict(list)  
  13.     for item in sorted(data['updated'], key=lambda x: x['chapterUid']):  
  14.         # for item in data['updated']:  
  15.         chapter = item['chapterUid']  
  16.         text = item['markText']  
  17.         create_time = item["createTime"]  
  18.         start = int(item['range'].split('-')[0])  
  19.         contents[chapter].append((start, text))  
  20.     chapters_map = {title: level for level, title in get_chapters(int(bookId), headers)}  
  21.     res = '' 
  22.      for c in sorted(chapters.keys()):  
  23.         title = chapters[c]  
  24.         res += '#' * chapters_map[title] + ' ' + title + '\n'  
  25.         for start, text in sorted(contents[c], key=lambda e: e[0]):  
  26.             res += '> ' + text.strip() + '\n\n'  
  27.         res += '\n'  
  28.     return res 

该函数的代码流程为:

如何运行

  1. # 跳转到当前目录  
  2. cd 目录名  
  3. # 先卸载依赖库  
  4. pip uninstall -y -r requirement.txt  
  5. # 再重新安装依赖库  
  6. pip install -r requirement.txt -i https://pypi.tuna.tsinghua.edu.cn/simple  
  7. # 开始运行  
  8. python pyqt_gui.py 

补充

完整版源代码存放在github上,有需要的请点击这里下载

https://github.com/shengqiangzhang/examples-of-web-crawlers

评论关闭