前言
這里以爬取博客園文章為例,僅供學(xué)習(xí)參考,某些AD滿天飛的網(wǎng)站太浪費(fèi)爬蟲的感情了。
爬取
*
使用 BeautifulSoup 獲取博文
*
通過 html2text 將 Html 轉(zhuǎn) Markdown
*
保存 Markdown 到本地文件
*
下載 Markdown 中的圖片到本地并替換圖片地址
*
寫入數(shù)據(jù)庫(kù)
工具
使用到的第三方類庫(kù):BeautifulSoup、html2text、PooledDB
代碼
獲取博文:
# 獲取標(biāo)題和文章內(nèi)容 def getHtml(blog): res = requests.get(blog, headers=headers) soup
= BeautifulSoup(res.text, 'html.parser') # 獲取博客標(biāo)題 title = soup.find('h1',
class_='postTitle').text # 去除空格等 title = title.strip() # 獲取博客內(nèi)容 content =
soup.find('div', class_='blogpost-body') # 去掉博客外層的DIV content =
article.decode_contents(formatter="html") info = {"title": title, "content":
content} return info
Html 轉(zhuǎn) Markdown:
# 這里使用開源第三方庫(kù) html2text md = text_maker.handle(info['content'])
保存到本地文件:
def createFile(md, title):
print('系統(tǒng)默認(rèn)編碼:{}'.format(sys.getdefaultencoding())) save_file = str(title)
+".md" # print(save_file) print('準(zhǔn)備寫入文件:{}'.format(save_file)) # r+
打開一個(gè)文件用于讀寫。文件指針將會(huì)放在文件的開頭。 # w+ 打開一個(gè)文件用于讀寫。如果該文件已存在則將其覆蓋。如果該文件不存在,創(chuàng)建新文件。 # a+
打開一個(gè)文件用于讀寫。如果該文件已存在,文件指針將會(huì)放在文件的結(jié)尾。文件打開時(shí)會(huì)是追加模式。如果該文件不存在,創(chuàng)建新文件用于讀寫。 f =
codecs.open(save_file, 'w+', 'utf-8') f.write(md) f.close()
print('寫入文件結(jié)束:{}'.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 #
日期時(shí)間為目錄存儲(chǔ)圖片 dir_ts = time.strftime('%Y%m', time.localtime()) isExists =
os.path.exists(dir_ts) # 判斷結(jié)果 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 #
如果有內(nèi)容的話,就直接覆蓋寫入當(dāng)前的markdown文件 if post and cnt_replace > 0: url =
"https://blog.52itstyle.vip" open(md_file, 'w', encoding='utf-8').write(post)
print('{0}的{1}個(gè)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)))
寫入數(shù)據(jù)庫(kù):
# 寫入數(shù)據(jù)庫(kù) 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)
小結(jié)
互聯(lián)網(wǎng)時(shí)代一些開放的博客社區(qū)的確方便了很多,但是也伴隨著隨時(shí)消失的可能性,最好就是自己備份一份到本地;你也可以選擇自己喜歡的博主,爬取下收藏。
源碼:https://gitee.com/52itstyle/Python <https://gitee.com/52itstyle/Python>
演示:https://blog.52itstyle.top <https://blog.52itstyle.top/>
列表:https://blog.52itstyle.top/index <https://blog.52itstyle.top/index>
詳情:https://blog.52itstyle.top/49.shtml <https://blog.52itstyle.top/49.shtml>
熱門工具 換一換