1. 程式人生 > >python3 用requests 保存網頁以及BeautifulSoup保存圖片,並且在本地可以正常顯示文章的內容和圖片

python3 用requests 保存網頁以及BeautifulSoup保存圖片,並且在本地可以正常顯示文章的內容和圖片

-s bs4 圖片保存 ins date xml解析 站點 mkdir post

用requests 模塊做了個簡單的爬蟲小程序,將博客的一篇文章以及圖片保存到本地,文章格式存為‘.html‘。當文章保存到本地後,圖片的連接可能是目標站點的絕對或者相對路徑,所以要是想在本地也顯示圖片,需要將保存下來圖片的本地路徑替換到本地的html文件裏。

保存網頁用的時requests模塊,保存圖片用的時BeautifulSoup, 這兩個都是第三方模塊,需要安裝,使用時需要手動導入。

**安裝方式:

pip install requsts

在python3 可能用 pip install beautifulsoup 會報錯,可以直接pip install bs4, 這樣時可以成功安裝的。

因為其實beautifulsoup 在bs4安裝包中,使用的時候采用:from bs4 import beautifulsoup

具體的代碼如下:

 1 from bs4 import BeautifulSoup
 2 import requests,os
 3 targetDir = os.path.join(os.path.dirname(os.path.abspath(__file__)),imgs1)#圖片保存的路徑,eg,向前文件夾為‘D:\Coding‘, 即圖片保存在‘D:\Coding\imgs1\‘
 4 if not os.path.isdir(targetDir):#
不存在創建路徑 5 os.mkdir(targetDir) 6 url = http://www.cnblogs.com/nancyzhu/p/8146408.html 7 domain = http://www.cnblogs.com 8 #保存頁面到本地 9 def save_html(): 10 r_page = requests.get(url) 11 f = open(page.html,wb) 12 f.write(r_page.content)#save to page.html 13 f.close() 14 return
r_page 15 #修改文件,將圖片路徑改為本地的路徑 16 def update_file(old,new): 17 with open(page.html, encoding=utf-8) as f, open(page_bak.html, w, 18 encoding=utf-8) as fw: # 打開兩個文件,原始文件用來讀,另一個文件將修改的內容寫入 19 for line in f: # 遍歷每行,取出來的是字符串,因此可以用replace 方法替換 20 new_line = line.replace(old, new) # 逐行替換 21 fw.write(new_line) # 寫入新文件 22 os.remove(page.html) # 刪除原始文件 23 os.rename(page_bak.html, page.html) # 修改新文件名, old -> new 24 #保存圖片到本地 25 def save_file_to_local(): 26 obj = BeautifulSoup(save_html().content, lxml) # 後面是指定使用lxml解析,lxml解析速度比較快,容錯高。 27 imgs = obj.find_all(img) 28 #將頁面上圖片的鏈接加入list 29 urls = [] 30 for img in imgs: 31 if data-src in str(img): 32 urls.append(img[data-src]) 33 else: 34 urls.append(img[src]) 35 #遍歷所有圖片鏈接,將圖片保存到本地指定文件夾,圖片名字用0,1,2... 36 i = 0 37 for url in urls:#看下文章的圖片有哪些格式,一一處理 38 if url.startswith(//): 39 new_url = http: + url 40 r = requests.get(new_url) 41 elif url.startswith(/) and url.endswith(gif): 42 new_url = domain + url 43 r = requests.get(new_url) 44 elif url.endswith(.png) or url.endswith(jpg) or url.endswith(gif): 45 r = requests.get(url) 46 t = os.path.join(targetDir, str(i) + .jpg)#指定目錄 47 fw = open(t,wb) # 指定絕對路徑 48 fw.write(r.content)#保存圖片到本地指定目錄 49 i += 1 50 update_file(url,t)#將老的鏈接(有可能是相對鏈接)修改為本地的鏈接,這樣本地打開整個html就能訪問圖片 51 fw.close() 52 53 if __name__ == __main__: 54 save_html() 55 save_file_to_local()

python3 用requests 保存網頁以及BeautifulSoup保存圖片,並且在本地可以正常顯示文章的內容和圖片