title: 《小·意·思》爬取頁面圖片并保存
date: 2023-08-10 22:12:30
updated: 2023-08-29 17:07:55
categories: 番外:小·意·思
excerpt: 上下標(biāo)號、標(biāo)點(diǎn)、運(yùn)算符、標(biāo)號、時(shí)間相關(guān)、語言、貨幣、音樂、形狀符號、其他符號。
comments: false
tags:
top_image: /images/backimg/SunsetClimbing.png
簡單的爬取圖片
前言
這幾天打算整理與遷移一下博客。因?yàn)?CSDN 的 Markdown 編輯器很好用 ,所以全部文章與相關(guān)圖片都保存在 CSDN。而且 CSDN 支持一鍵導(dǎo)出自己的文章為 markdown 文件。但導(dǎo)出的文件中圖片的連接依舊是 url 連接。為了方便將圖片保存到本地,在這里保存一下爬蟲代碼。
只要修改正則匹配代碼,同樣適用于博客園爬取。
代碼
為了提高效率,該腳本將從保存的本地 markdown 文件讀取圖片鏈接。當(dāng)然腳本中也保留了爬取某個(gè)頁面所有圖片的函數(shù)。
腳本名:spider.py
import urllib.request
import urllib.parse
import sys
import os
import re
def open_url(url):
'''
用于網(wǎng)頁爬取。這里不采用這個(gè)函數(shù)
'''
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0')
# 訪問url,并將頁面的二進(jìn)制數(shù)據(jù)賦值給 page
page = urllib.request.urlopen(req)
# 將page中的內(nèi)容轉(zhuǎn)換為utf-8編碼
html = page.read().decode('utf-8')
return html
def read_file(file):
print('\n正在讀取文件...')
with open(file, 'rb') as my_file:
content = my_file.read()
content = content.decode('utf-8')
print('已讀取文件.')
return content
def get_img(content, file_path):
# 正則匹配圖片鏈接
# p=r'<img src="([^"]+\.png)"' # 可用于網(wǎng)頁爬取
p=r'https://img-blog\.csdnimg\.cn/[\w\-/]+\.(?:png|jpg|jpeg)'
#返回正則表達(dá)式在字符串中所有匹配結(jié)果的列表
print('\n正在讀取圖片鏈接...')
img_list=re.findall(p, content)
list_len = str(len(img_list))
print('已讀取圖片鏈接.\n')
for img_url in img_list:
print(img_url)
print('\n共 ' + list_len + ' 條數(shù)據(jù)')
# 圖片保存位置。如果文件夾不存在則創(chuàng)建
save_path = file_path + '/assets/'
if not os.path.exists(save_path):
os.makedirs(save_path)
print('\n正在保存圖片...\n')
num = 0 # 用于記錄進(jìn)度
for each in img_list:
#以 / 為分隔符,-1返回最后一個(gè)值
photo_name=each.split("/")[-1]
#訪問 each,并將頁面的二進(jìn)制數(shù)據(jù)賦值給photo
photo=urllib .request .urlopen(each)
w=photo .read()
# f=open(save_path + photo_name + '.png', 'wb')
f=open(save_path + photo_name, 'wb')
f.write(w)
f.close()
# 展示進(jìn)度
print(num % 10, end="")
if (num + 1) % 10 == 0 and num != 0:
print(' 進(jìn)度: ' + str(num + 1) + '/' + list_len)
sys.stdout.flush() # 刷新輸出緩沖
num += 1
print('\n\n完成!\n')
if __name__=='__main__':
if len(sys.argv) != 2:
print("\nUsage: python spider.py <file>")
print('example: python spider.py "F:\\T\\test.md"')
sys.exit()
file = str(sys.argv[1])
file_name = os.path.basename(file)
file_path = os.path.dirname(file)
print('\nfile_name: ' + file_name)
print('file_path: ' + file_path)
# 讀取文件內(nèi)容
content = read_file(file)
# 爬取圖片
get_img(content, file_path)
效果
別后相思人似月,云間水上到層城。 文章來源:http://www.zghlxwxcb.cn/news/detail-638784.html
——《明月夜留別》(唐)李冶 文章來源地址http://www.zghlxwxcb.cn/news/detail-638784.html
到了這里,關(guān)于《爬蟲》爬取頁面圖片并保存的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!