者: Nealyang
轉發鏈接:https://mp.weixin.qq.com/s/exR8W8jXxGfZTpx9jB0SSQ
主要利用了H5的canvas功能,分為 2個js文件 html2canvas.js和canvas2image.js
項目源碼的壓縮包會在文章的最底部分享給大家。
界面代碼如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>html2image</title>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="./html2canvas.js"></script>
<script src="./canvas2image.js"></script>
<script>
$(document).ready(function () {
$("#saveAsImage").click(function (e) {
saveHtml2Image("div1", 1);
});
});
function saveHtml2Image(objId, scale) {
document.body.scrollTop=0;
var obj=$("body");
var width=obj.width();;
var height=obj.height();
var scaledCanvas=document.createElement("canvas");
scaledCanvas.width=width;
scaledCanvas.height=height;
scaledCanvas.style.width=width + "px";
scaledCanvas.style.height=height + "px";
var scaledContext=scaledCanvas.getContext("2d");
scaledContext.scale(1, 1);
var width=$(window).width();
var height=$(window).height();
html2canvas(obj, {
canvas: scaledCanvas,
width: width,
height: height,
background: "rgba(255,255,255,1)",
allowTaint:true,
onrendered: function (canvas) {
var dataUrl=Canvas2Image.saveAsJPEG(canvas, parseInt(width * scale), parseInt(height * scale));
obj.html("<img src='"+dataUrl+"' crossOrigin='anonymous'>")
}
});
}
</script>
</head>
<body id="div1" style="width:400px">
<div style="color:red;padding:10px 10px;" style="width:400px">
<div>
<span>
我要變圖片
</span>
</div>
<div style="clear:both;"></div>
<div>
<span>
我要變圖片
</span>
</div>
<div style="clear:both;"></div>
<input type="button" value="saveHtmlAsImage" id="saveAsImage" />
<a href="" id="downloadImage" style="display:none;">downloadImage</a>
</div>
</body>
</html>
次為大家介紹了如果用 Python 抓取公號文章并保存成 PDF 文件存儲到本地。但用這種方式下載的 PDF 只有文字沒有圖片,所以只適用于沒有圖片或圖片不重要的公眾號,那如果我想要圖片和文字下載下來怎么辦?今天就給大家介紹另一種方案——HTML。
其實我們要解決的有兩個問題:
綜上問題,我覺得還是把公眾號下載成網頁 HTML 格式最好看,下面就介紹下如何實現。
獲取文章鏈接的方式,和上一篇下載成 PDF 的文章一樣,依然是通過公眾號平臺的圖文素材里超鏈接查詢實現,在這里我們直接拿來上一期的代碼,進行修改即可。首先將原來文件 gzh_download.py 復制成 gzh_download_html.py,然后在此基礎進行代碼改造:
# gzh_download_html.py
# 引入模塊
import requests
import json
import re
import time
from bs4 import BeautifulSoup
import os
# 打開 cookie.txt
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)
# 從url中獲取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",
}
# 循環遍歷前10頁的文章
for j in range(1, 10, 1):
begin=(j-1)*5
# 請求當前頁獲取文章列表
requestUrl="https://mp.weixin.qq.com/cgi-bin/appmsg?action=list_ex&begin="+str(begin)+"&count=5&fakeid=MzU1NDk2MzQyNg==&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 i in list:
# 目錄名為標題名,目錄下存放 html 和圖片
dir_name=i["title"].replace(' ','')
print("正在下載文章:" + dir_name)
# 請求文章的 url ,獲取文章內容
response=requests.get(i["link"], cookies=cookies, headers=headers)
# 保存文章到本地
save(response, dir_name, i["aid"])
print(dir_name + "下載完成!")
# 過快請求可能會被微信問候,這里進行10秒等待
time.sleep(10)
好了,從上面代碼可以看出,主要就是將原來的方法 pdfkit.from_url(i["link"], i["title"] + ".pdf") 改成了現在的方式,需要用 requests 請求下文章的 URL ,然后再調用保存文章頁面和圖片到本地的方法,這里的 save() 方法通過以下代碼實現。
#保存下載的 html 頁面和圖片
def save(search_response,html_dir,file_name):
# 保存 html 的位置
htmlDir=os.path.join(os.path.dirname(os.path.abspath(__file__)), html_dir)
# 保存圖片的位置
targetDir=os.path.join(os.path.dirname(os.path.abspath(__file__)),html_dir + '/images')
# 不存在創建文件夾
if not os.path.isdir(targetDir):
os.makedirs(targetDir)
domain='https://mp.weixin.qq.com/s'
# 調用保存 html 方法
save_html(search_response, htmlDir, file_name)
# 調用保存圖片方法
save_file_to_local(htmlDir, targetDir, search_response, domain)
# 保存圖片到本地
def save_file_to_local(htmlDir,targetDir,search_response,domain):
# 使用lxml解析請求返回的頁面
obj=BeautifulSoup(save_html(search_response,htmlDir,file_name).content, 'lxml')
# 找到有 img 標簽的內容
imgs=obj.find_all('img')
# 將頁面上圖片的鏈接加入list
urls=[]
for img in imgs:
if 'data-src' in str(img):
urls.append(img['data-src'])
elif 'src=""' in str(img):
pass
elif "src" not in str(img):
pass
else:
urls.append(img['src'])
# 遍歷所有圖片鏈接,將圖片保存到本地指定文件夾,圖片名字用0,1,2...
i=0
for each_url in urls:
# 跟據文章的圖片格式進行處理
if each_url.startswith('//'):
new_url='https:' + each_url
r_pic=requests.get(new_url)
elif each_url.startswith('/') and each_url.endswith('gif'):
new_url=domain + each_url
r_pic=requests.get(new_url)
elif each_url.endswith('png') or each_url.endswith('jpg') or each_url.endswith('gif') or each_url.endswith('jpeg'):
r_pic=requests.get(each_url)
# 創建指定目錄
t=os.path.join(targetDir, str(i) + '.jpeg')
print('該文章共需處理' + str(len(urls)) + '張圖片,正在處理第' + str(i + 1) + '張……')
# 指定絕對路徑
fw=open(t, 'wb')
# 保存圖片到本地指定目錄
fw.write(r_pic.content)
i +=1
# 將舊的鏈接或相對鏈接修改為直接訪問本地圖片
update_file(each_url, t, htmlDir)
fw.close()
# 保存 HTML 到本地
def save_html(url_content,htmlDir,file_name):
f=open(htmlDir+"/"+file_name+'.html', 'wb')
# 寫入文件
f.write(url_content.content)
f.close()
return url_content
# 修改 HTML 文件,將圖片的路徑改為本地的路徑
def update_file(old, new,htmlDir):
# 打開兩個文件,原始文件用來讀,另一個文件將修改的內容寫入
with open(htmlDir+"/"+file_name+'.html', encoding='utf-8') as f, open(htmlDir+"/"+file_name+'_bak.html', 'w', encoding='utf-8') as fw:
# 遍歷每行,用replace()方法替換路徑
for line in f:
new_line=line.replace(old, new)
new_line=new_line.replace("data-src", "src")
# 寫入新文件
fw.write(new_line)
# 執行完,刪除原始文件
os.remove(htmlDir+"/"+file_name+'.html')
time.sleep(5)
# 修改新文件名為 html
os.rename(htmlDir+"/"+file_name+'_bak.html', htmlDir+"/"+file_name+'.html')
好了,上面就是將文章頁面和圖片下載到本地的代碼,接下來我們運行命令 python gzh_download_html.py ,程序開始執行,打印日志如下:
$ python gzh_download_html.py
正在下載文章:學習Python看這一篇就夠了!
該文章共需處理3張圖片,正在處理第1張……
該文章共需處理3張圖片,正在處理第2張……
該文章共需處理3張圖片,正在處理第3張……
學習Python看這一篇就夠了!下載完成!
正在下載文章:PythonFlask數據可視化
該文章共需處理2張圖片,正在處理第1張……
該文章共需處理2張圖片,正在處理第2張……
PythonFlask數據可視化下載完成!
正在下載文章:教你用Python下載手機小視頻
該文章共需處理11張圖片,正在處理第1張……
該文章共需處理11張圖片,正在處理第2張……
該文章共需處理11張圖片,正在處理第3張……
該文章共需處理11張圖片,正在處理第4張……
該文章共需處理11張圖片,正在處理第5張……
該文章共需處理11張圖片,正在處理第6張……
該文章共需處理11張圖片,正在處理第7張……
現在我們去程序存放的目錄,就能看到以下都是以文章名稱命名的文件夾:
進入相應文章目錄,可以看到一個 html 文件和一個名為 images 的圖片目錄,我們雙擊打開擴展名為 html 的文件,就能看到帶圖片和代碼框的文章,和在公眾號看到的一樣。
本文為大家介紹了如何通過 Python 將公號文章批量下載到本地,并保存為 HTML 和圖片,這樣就能實現文章的離線瀏覽了。當然如果你想將 HTML 轉成 PDF 也很簡單,直接用 pdfkit.from_file(xx.html,target.pdf) 方法直接將網頁轉成 PDF,而且這樣轉成的 PDF 也是帶圖片的。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。