python 爬取資訊文章並儲存html及pdf格式
阿新 • • 發佈:2018-12-26
一、需求
研究生學長讓我把一個植物表型資訊系列文章的一系列文章爬下來儲存為pdf或者html格式。
首頁網址:
https://mp.weixin.qq.com/s?__biz=MzI0Mjg5ODI1Ng==&mid=2247486022&idx=1&sn=5f7c9aff1e3f1847812ce92304a3affc&chksm=e9740e79de03876fffc5ca39f70c105298acf5d2329d632e69cb997f8a07ba1234f97c91464c&scene=21#wechat_redirect
二、思路分析
列表的每一篇文章都應該是一個連結,因此先將首頁儲存下來分析其元素結構
找到各連結所在主體<div>
元素<div class="rich_media_content " id="js_content">
記錄
確認每一個文章連結都在都是<a>
元素
因此思路就是 先獲得主體塊中的連結標籤,根據文章名和連結儲存每一篇文章。
三 、難點
難點在於儲存pdf時,圖片是要儲存在pdf之中的,因此如果文章介面圖片如果是是懶載入的時候,爬取的文章儲存位html和pdf 圖片都將會是空白的。
因此先去分析文章中圖片的載入形式
選一篇文章分析:
可以看到圖片載入採用的是
data-src
載入的,因此需要將每一個<img>
的標籤t圖片連結改成src
形式。
四、採用工具
import requests//用來請求獲得頁面
import pdfkit// 用來儲存成pdf格式
from bs4 import BeautifulSoup//用來將html劃分成各標籤進行處理
五、原始碼
# -*- coding:UTF-8 -*-
import time
import requests
import pdfkit
import re
from bs4 import BeautifulSoup
# 模版
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
{content}
</body>
</html>
"""
def save_pdfs(a):
i=0
for each in a:
i=i+1
if i>0: # 如果因為某種原因中斷後可以根據已經下載的篇數設定i值從第i篇開始
if each.string != None:
rstr = r"[\/\\\:\*\?\"\<\>\|]" # '/ \ : * ? " < > |' #存到本地 剔除特殊符號
each.string = re.sub(rstr, "_", each.string)
file_name = "E:\\pdf1\\" + each.string + ".pdf"
html_name = "E:\\html1\\" + each.string + ".html"
path_wk = r'D:\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wk) # windows需要進行此配置 才能轉化pdf
options = {
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'no-outline': None
}
target = each.get('href')
time.sleep(4) # 設定強制睡眠時間減少IP被禁的可能性
page = requests.get(url=target)
soup = BeautifulSoup(page.content, 'html.parser')
article = soup.select('.rich_media_content')[0]# 選擇主體部分下載
for img in article.find_all('img'):
img['src'] = img['data-src'] ##!!!將所有的懶載入改成直接載入
article = str(article)
html = html_template.format(content=article)
html = html.encode('utf-8')
with open(html_name, 'wb') as f:
f.write(html) # 儲存html格式
try: # 儲存pdf格式
pdfkit.from_file(html_name, file_name, configuration=config, options=options) # 轉化成pdf格式
except Exception as e:
print(e)
def main():
target = 'https://mp.weixin.qq.com/s?__biz=MzI0Mjg5ODI1Ng==&mid=2' \
'247486022&idx=1&sn=5f7c9aff1e3f1847812ce92304a3affc&chksm=e9' \
'740e79de03876fffc5ca39f70c105298acf5d2329d632e69cb997f8a07ba \
1234f97c91464c&scene=21#wechat_redirect'
req = requests.get(url=target)
html = req.text
div_bf = BeautifulSoup(html)
div = div_bf.find_all('div', class_='rich_media_content')
a_bf = BeautifulSoup(str(div[0]))
a = a_bf.find_all('a')# 獲得主頁面的所有連結標籤
save_pdfs(a)
if __name__ == "__main__":
main()
六、效果展示
其中一篇pdf,可以看到是帶有圖片的。