前言
這里以爬取博客園文章為例,僅供學習參考,某些AD滿天飛的網站太浪費爬蟲的感情了。
爬取
-
使用 BeautifulSoup 獲取博文
-
通過 html2text 將 Html 轉 Markdown
-
保存 Markdown 到本地文件
-
下載 Markdown 中的圖片到本地並替換圖片地址
-
寫入數據庫
工具
使用到的第三方類庫:BeautifulSoup、html2text、PooledDB
代碼
獲取博文:
# 獲取標題和文章內容
def getHtml(blog):
res = requests.get(blog, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
# 獲取博客標題
title = soup.find('h1', class_='postTitle').text
# 去除空格等
title = title.strip()
# 獲取博客內容
content = soup.find('div', class_='blogpost-body')
# 去掉博客外層的DIV
content = article.decode_contents(formatter="html")
info = {"title": title, "content": content}
return info
Html 轉 Markdown:
# 這里使用開源第三方庫 html2text
md = text_maker.handle(info['content'])
保存到本地文件:
def createFile(md, title):
print('系統默認編碼:{}'.format(sys.getdefaultencoding()))
save_file = str(title) +".md"
# print(save_file)
print('准備寫入文件:{}'.format(save_file))
# r+ 打開一個文件用於讀寫。文件指針將會放在文件的開頭。
# w+ 打開一個文件用於讀寫。如果該文件已存在則將其覆蓋。如果該文件不存在,創建新文件。
# a+ 打開一個文件用於讀寫。如果該文件已存在,文件指針將會放在文件的結尾。文件打開時會是追加模式。如果該文件不存在,創建新文件用於讀寫。
f = codecs.open(save_file, 'w+', 'utf-8')
f.write(md)
f.close()
print('寫入文件結束:{}'.format(f.name))
return save_file
下載圖片到本地並替換圖片地址:
def replace_md_url(md_file):
"""
把指定MD文件中引用的圖片下載到本地,並替換URL
"""
if os.path.splitext(md_file)[1] != '.md':
print('{}不是Markdown文件,不做處理。'.format(md_file))
return
cnt_replace = 0
# 日期時間為目錄存儲圖片
dir_ts = time.strftime('%Y%m', time.localtime())
isExists = os.path.exists(dir_ts)
# 判斷結果
if not isExists:
os.makedirs(dir_ts)
with open(md_file, 'r', encoding='utf-8') as f: # 使用utf-8 編碼打開
post = f.read()
matches = re.compile(img_patten).findall(post)
if matches and len(matches) > 0:
for match in list(chain(*matches)):
if match and len(match) > 0:
array = match.split('/')
file_name = array[len(array) - 1]
file_name = dir_ts + "/" + file_name
img = requests.get(match, headers=headers)
f = open(file_name, 'ab')
f.write(img.content)
new_url = "https://blog.52itstyle.vip/{}".format(file_name)
# 更新MD中的URL
post = post.replace(match, new_url)
cnt_replace = cnt_replace + 1
# 如果有內容的話,就直接覆蓋寫入當前的markdown文件
if post and cnt_replace > 0:
url = "https://blog.52itstyle.vip"
open(md_file, 'w', encoding='utf-8').write(post)
print('{0}的{1}個URL被替換到{2}/{3}'.format(os.path.basename(md_file), cnt_replace, url, dir_ts))
elif cnt_replace == 0:
print('{}中沒有需要替換的URL'.format(os.path.basename(md_file)))
寫入數據庫:
# 寫入數據庫
def write_db(title, content, url):
sql = "INSERT INTO blog (title, content,url) VALUES(%(title)s, %(content)s, %(url)s);"
param = {"title": title, "content": content, "url": url}
mysql.insert(sql, param)
小結
互聯網時代一些開放的博客社區的確方便了很多,但是也伴隨着隨時消失的可能性,最好就是自己備份一份到本地;你也可以選擇自己喜歡的博主,爬取下收藏。
源碼:https://gitee.com/52itstyle/Python