1. 程式人生 > >Python3爬蟲學習4:降爬取的資訊儲存到本地

Python3爬蟲學習4:降爬取的資訊儲存到本地

將爬取的資訊儲存到本地

之前我們都是將爬取的資料直接列印到了控制檯上,這樣顯然不利於我們對資料的分析利用,也不利於儲存,所以現在就來看一下如何將爬取的資料儲存到本地硬碟。

1.對.txt檔案的操作

讀寫檔案是最常見的操作之一,python3 內建了讀寫檔案的函式:open

open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None))
Open file and return a corresponding file object. If the file cannot be opened, an OSError
is raised.

其中比較常用的引數為file和mode,引數file為檔案的路徑,引數mode為操作檔案的方式(讀/寫),函式的返回值為一個file物件,如果檔案操作出現異常的話,則會丟擲 一個OSError

還以簡書首頁文章題目為例,將爬取到的文章標題存放到一個.txt檔案中,具體程式碼如下:

# -*- coding:utf-8 -*-

from urllib import request
from bs4 import BeautifulSoup

url = r'http://www.jianshu.com'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') soup = BeautifulSoup(page_info, 'html.parser') titles = soup.find_all('a', 'title') try: # 在E盤以只寫的方式開啟/建立一個名為 titles 的txt檔案 file = open(r'E:\titles.txt', 'w') for title in titles: # 將爬去到的文章題目寫入txt中
file.write(title.string + '\n') finally: if file: # 關閉檔案(很重要) file.close()

open中mode引數的含義見下表:

符號 含義
‘r’ 以只讀模式開啟檔案(預設模式)
‘w’ 以只寫的方式開啟檔案,如果檔案存在的話會先刪除再重新建立
‘x’ 以獨佔的方式開啟檔案,如果檔案已經存在則錯誤
‘a’ 以寫的形式開啟檔案,若檔案已存在,則以追加的方式寫入
‘b’ 二進位制模式
‘t’ 文字模式(預設)
‘+’ 更新檔案(讀/寫)

其中’t’為預設模式,’r’相當於’rt’,符號可以疊加使用,像’r+b’

另外,對檔案操作一定要注意的一點是:開啟的檔案一定要關閉,否則會佔用相當大的系統資源,所以對檔案的操作最好使用try:…finally:…的形式。但是try:…finally:…的形式會使程式碼顯得比較雜亂,所幸python中的with語句可以幫我們自動呼叫close()而不需要我們寫出來,所以,上面程式碼中的try:…finally:…可使用下面的with語句來代替:

with open(r'E:\title.txt', 'w') as file:
    for title in titles:
        file.write(title.string + '\n')

效果是一樣的,建議使用with語句
這裡寫圖片描述
2 圖片的儲存

有時候我們的爬蟲不一定只是爬取文字資料,也會爬取一些圖片,下面就來看怎麼將爬取的圖片存到本地磁碟。
我們先來選好目標,知乎話題:女生怎麼健身鍛造好身材? (單純因為圖多,不要多想哦 (# _ # ) )

看下頁面的原始碼,找到話題下圖片連結的格式,如圖:
這裡寫圖片描述
可以看到,圖片在img標籤中,且class=origin_image zh-lightbox-thumb,而且連結是由.jpg結尾,我們便可以用Beautiful Soup結合正則表示式的方式來提取所有連結,如下:

links = soup.find_all('img', "origin_image zh-lightbox-thumb",src=re.compile(r'.jpg$'))

提取出所有連結後,使用request.urlretrieve來將所有連結儲存到本地

Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers)
where filename is the local file name under which the object can be found, and headers is whatever the info()
method of the object returned by urlopen()
returned (for a remote object). Exceptions are the same as for urlopen()
.

具體實現程式碼如下:

# -*- coding:utf-8 -*-
import time
from urllib import request
from bs4 import BeautifulSoup
import re

url = r'https://www.zhihu.com/question/22918070'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
page = request.Request(url, headers=headers)
page_info = request.urlopen(page).read().decode('utf-8')
soup = BeautifulSoup(page_info, 'html.parser')

# Beautiful Soup和正則表示式結合,提取出所有圖片的連結(img標籤中,class=**,以.jpg結尾的連結)
links = soup.find_all('img', "origin_image zh-lightbox-thumb",src=re.compile(r'.jpg$'))
# 設定儲存的路徑,否則會儲存到程式當前路徑
local_path = r'E:\Pic'

for link in links:
    print(link.attrs['src'])
    # 儲存連結並命名,time防止命名衝突
    request.urlretrieve(link.attrs['src'], local_path+r'\%s.jpg' % time.time())

執行結果:
這裡寫圖片描述