Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to export Wechat reading records and notes with one click

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use Python to export Wechat reading records and notes". In daily operation, I believe many people have doubts about how to use Python to export Wechat reading records and notes. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use Python to export Wechat reading records and notes". Next, please follow the editor to study!

1. Directory structure

First, let's take a look at the overall directory structure.

├─ excel_func.py reads and writes excel files ├─ pyqt_gui.py PyQt GUI interface └─ wereader.py Wechat Reading related api

Excel_func.py

Use xlrd and xlwt libraries to read and write excel files

Pyqt_gui.py

Using PyQt to draw GUI interface

Wereader.py

Obtain the relevant api through packet analysis

2. Excel_func.py

Def write_excel_xls (path, sheet_name_list Value): # create a new workbook workbook = xlwt.Workbook () # get the number of rows that need to be written index = len (value) for sheet_name in sheet_name_list: # create a new table in the workbook sheet = workbook.add_sheet (sheet_name) # write data for i in range to the table in this workbook (0 Index): for j in range (0, len (value [I])): sheet.write (I, j, value [I] [j]) # Save workbook workbook.save (path)

The code flow of this function is:

Create an excel file

Create a table

Write data to a table

3. Pyqt_gui.py

Class MainWindow (QMainWindow): def _ init__ (self, * args, * * kwargs): super (). _ init__ (* args, * * kwargs) self.DomainCookies = {} self.setWindowTitle ('Wechat Reading Assistant') # set window title self.resize # set the window size self.setWindowFlags (Qt.WindowMinimizeButtonHint) # disable the maximize button self.setFixedSize (self.width () Self.height () # prohibit window resizing url = 'https://weread.qq.com/#login' # destination address self.browser = QWebEngineView () # instantiate browser object QWebEngineProfile.defaultProfile (). CookieStore () .deleteAllCookies () # remove all cookies QWebEngineProfile.defaultProfile () .cookieStore () .cookieAdded.connect (self) when you run the software for the first time .onCookieAdd) # trigger self.onCookieAdd () function self.browser.loadFinished.connect (self.onLoadFinished) when cookies is added # trigger self.onLoadFinished () function self.browser.load (QUrl (url)) # load web page self.setCentralWidget (self.browser) # set up the central window when the web page is loaded

The code flow of this function is:

Create a new QT window

Instantiate QWebEngineView object

Bind self.onCookieAdd event

Bind self.onLoadFinished event

Load a web page

# Web page loading event def onLoadFinished (self): global USER_VID global HEADERS # get cookies cookies = ['{} = {} '.format (key, value) for key Value in self.DomainCookies.items ()] cookies = '.join (cookies) # add Cookie to header HEADERS.update (Cookie=cookies) # determine whether you have successfully logged in to Wechat to read if login_success (HEADERS): print (' login Wechat read successfully!') # get the user user_vid If 'wr_vid' in self.DomainCookies.keys (): USER_VID = self.DomainCookies [' wr_vid'] print ('user id: {}' .format (USER_VID)) # close the entire qt window self.close () else: print ('scan two, please The Wiki code logs in to Wechat to read.')

The code flow of this function is:

When the web page is loaded, check whether you have successfully logged in to Wechat to read the book.

If you successfully log in to Wechat to read a book, close the QT window and start data export

If you fail to log in to Wechat to read, continue to wait for the user to scan the QR code

# add cookies event 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 code flow of this function is:

Save the cookies of the Wechat book URL for follow-up operation

Books = get_bookshelf (USER_VID, HEADERS) # get the books on the shelf booksbooks_finish_read = books ['finishReadBooks'] booksbooks_recent_read = books [' recentBooks'] booksbooks_all = books ['allBooks'] write_excel_xls_append (data_dir +' my shelf .xls', 'finished books' Books_finish_read) # append to excel file write_excel_xls_append (data_dir +'my bookshelf .xls', 'recent books', books_recent_read) # append to excel file write_excel_xls_append (data_dir +'my bookshelf .xls', 'all books' Books_all) # write to excel file # get notes for each book on the shelf for index, book in enumerate (books_finish_read): bookbook_id = book [0] bookbook_name = book [1] notes = get_bookmarklist (book [0], HEADERS) with open (note_dir + book_name + '.txt') 'w') as f: f.write (notes) print ('Export Notes {} ({} / {})' .format (note_dir + book_name + '.txt', index+1, len (books_finish_read)

The code flow of this function is:

Call the write_excel_xls_append function, save the book, and export the notes

4. Wereader.py

Def get_bookshelf (userVid, headers): "get all the books on the shelf"url =" https://i.weread.qq.com/shelf/friendCommon" params= dict (userViduserVid=userVid) r = requests.get (url, paramsparams=params, headersheaders=headers) Verify=False) if r.ok: data = r.json () else: raise Exception (r.text) books_finish_read = set () # finished books books_recent_read = set () # recently read books books_all = set () # all books on the shelf for book in data ['recentBooks']: If not book ['bookId'] .iskeeper (): # filter the official account 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)

The code flow of this function is:

Get recently read books, finished books, all books

Filter the official account section

Save book data in dictionary format

Def get_bookmarklist (bookId, headers): "" url = "https://i.weread.qq.com/book/bookmarklist" params= dict (bookIdbookId=bookId) r = requests.get (url, paramsparams=params, headersheaders=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_ mapping [title] +'+ title +'\ n' for start, text in sorted (contents [c] Key=lambda e: e [0]): res + ='>'+ text.strip () +'\ n\ n' res + ='\ n' return res

The code flow of this function is:

Get notes from a book

Rewrite the returned string to markdown format and output

How to run

# Jump to the current directory cd directory name # first uninstall the dependent library pip uninstall-y-r requirement.txt # and then reinstall the dependent library pip install-r requirement.txt-I https://pypi.tuna.tsinghua.edu.cn/simple # start running python pyqt_gui.py, this is the end of the study on "how to use Python to export Wechat reading records and notes". I hope to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report