如今咱們大多數人都會或多或少的關注幾個公衆號,若是發現一個比較合本身胃口的號
對公衆號中的文章必定是每篇必讀的。css
有時候咱們關注到寶藏型公衆號時發現其歷史文章已經好幾百甚至上千篇了,而做者又只對其中本身認爲比較好的幾篇作了索引,咱們翻來翻去實在太麻煩了,爲了解決這種問題,我決定用 Python 將公衆號中文章爬下來。html
爬取公衆號文章列表信息,可獲取的信息主要包括文章連接、標題等python
利用 wechatsogou 模塊根據文章連接獲取文章 html 格式信息ajax
文章爬取咱們採用藉助公衆平臺的方式,這種方式雖然簡單,但須要咱們本身有一個公衆號,若是沒有公衆號能夠本身註冊一個,公衆號的註冊也比較簡單,這裏就不說了。json
首先,登陸本身的公衆號,而後依次進行以下操做
經過上面的操做,咱們能夠取到 cookie 等信息,咱們先將 cookie 寫入 txt 文件中,實現代碼以下所示:api
# 從瀏覽器中複製出來的 cookie 字符串 cookie_str = "本身的 cookie" cookie = {} # 遍歷 cookie for cookies in cookie_str.split("; "): cookie_item = cookies.split("=") cookie[cookie_item[0]] = cookie_item[1] # 將 cookie 寫入 txt 文件 with open('cookie.txt', "w") as file: file.write(json.dumps(cookie))
接着咱們獲取公衆號文章列表信息,代碼實現以下所示:瀏覽器
with open("cookie.txt", "r") as file: cookie = file.read() cookies = json.loads(cookie) url = "https://mp.weixin.qq.com" response = requests.get(url, cookies=cookies) # 獲取token token = re.findall(r"token=(\d+)", str(response.url))[0] # 請求頭信息 headers = { "Referer": "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=10&token=" + token + "&lang=zh_CN", "Host": "mp.weixin.qq.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36", } # 遍歷指定頁數的文章 for i in range(1, 5, 1): begin = (i - 1) * 5 # 獲取文章列表 requestUrl = "https://mp.weixin.qq.com/cgi-bin/appmsg?action=list_ex&begin="+str(begin)+"&count=5&fakeid=要爬取公衆號的fakeid&type=9&query=&token=" + token + "&lang=zh_CN&f=json&ajax=1" search_response = requests.get(requestUrl, cookies=cookies, headers=headers) # 獲取 JSON 格式的列表信息 re_text = search_response.json() list = re_text.get("app_msg_list") # 遍歷文章列表 for j in list: # 文章連接 url = j["link"] # 文章標題 title = j["title"] print(url) # 等待 8 秒,避免請求過於頻繁 time.sleep(8)
經過文章列表信息咱們能夠獲得公衆號文章連接、標題等信息,接着咱們就能夠經過 wechatsogou
模塊根據文章連接獲取文章的 html 格式信息了,模塊安裝使用 pip install wechatsogou
便可。微信
這裏須要注意一下,咱們經過 wechatsogou
模塊獲取的 html 信息會有一些問題,主要的問題有兩個,一是獲取文章的 html 信息不全,須要咱們本身補一下;另外一個是獲取的 html 信息可能會有一些 CSS 樣式沒有帶過來,這個問題咱們能夠先經過瀏覽器的開發者工具取到樣式,而後再手動添加一下就好了。代碼實現以下所示:cookie
# url:文章連接,title:文章標題 def save2html(url, title): # captcha_break_time 爲驗證碼輸入錯誤的重試次數,默認爲 1 ws_api = wechatsogou.WechatSogouAPI(captcha_break_time = 3) content_info = ws_api.get_article_content(url) html = f''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{title}</title> </head> <link href="my.css" rel="stylesheet" type="text/css" /> <body> <h2 style="text-align: center;font-weight: 400;">{title}</h2> {content_info['content_html']} </body> </html> ''' with open(title + '.html', "w", encoding="utf-8") as file: file.write('%s\n'%html)
上述代碼中 my.css
文件存放的就是一些沒有帶過來的 CSS 樣式信息。app
用瀏覽器打開一個公衆號文章的 html 文件看一下效果:
經過上面的顯示結果,能夠看出咱們保存的 html 文件的顯示效果還算比較好。
若是須要完整代碼,微信掃描識別文末二維碼,後臺回覆 200411 便可。
參考:https://mp.weixin.qq.com/s/jGjCfnGdxzK29FgC4E-_Cg