網絡爬蟲學習(一)
1、非結構化數據
沒有固定的數據格式,如網頁資料。必須透過ETL(Extract,Transormation,Loading)工具將數據轉化爲結構化數據才能取用。
(1)數據抽取、轉換、存儲(Data ETL)
(2)網絡爬蟲架構
2、使用開發人員工具
在網頁上點擊右鍵--->檢測
以新浪網站爲例:
刷新後的頁面如下圖所示
通過查看“Doc”對應的鏈接如china/中的內容是否和網頁中內容一致。
概括爲:
下面在Windows進行安裝配置,首先打開命令行工具
安裝過程如下:
(1)pip install requests
(2)pip install BeautifulSoup4
(3)安裝notebook
命令:pip install jupyter
安裝完成後,使用命令:jupyter notebook來啓動。會打開如下的頁面,它是一個本地的。
其開啓方法是選擇new--->python2(電腦上安裝的是python2.7.x)
新建完成後,顯示如下,即可在其中進行編寫。
3、撰寫第一隻網絡爬蟲
(1)代碼編寫
代碼:
import requests
res=requests.get('http://news.sina.com.cn/china/') #從上圖中Headers中的Request Method可知其是GET方法
res.encoding='utf-8' #使用utf-8進行編碼顯示纔不會亂碼print (res.text) #將內容顯示
(2)用BeautifulSoup 剖析網頁元素
BeautifulSoup範例
將網頁讀進BeautifulSoup中
from bs4 import BeautifulSoup html_sample=' \ <html> \ <body> \ <h1 id="title"> Hello World</h1> \ <a href="#" class="link">This is link1</a> \ <a href="# link2" class="link"> This is link2</a> \ </body> \ </html>'
soup=BeautifulSoup(html_sample,'html.parser')
print (soup.text)
運行後,報錯
好多人都是因爲python的問題。後面下載安裝了Anaconda的python3.6版本。之前別人也講用普通的python可能出現錯誤比較多,建議安裝Anaconda的python版本。
(安裝參考另一篇博客:Windows下安裝Anaconda和python)
後面選擇python3
然後,粘貼進代碼,運行即可正常。