教材:《Web Scraping with Python——Collecting Data from the Modern Web》? 2015 by Ryan Mitchell
網(wǎng)絡(luò)數(shù)據(jù)采集是一種通過多種手段收集網(wǎng)絡(luò)數(shù)據(jù)的方式,不光是通過與 API 交互(或者直接與瀏覽器交互)的方式。最常用的方法是寫一個自動化程序向網(wǎng)絡(luò)服務器請求數(shù)據(jù)(通常是用 HTML 表單或其他網(wǎng)頁文件),然后對數(shù)據(jù)進行解析,提取需要的信息。
實現(xiàn)一個網(wǎng)絡(luò)爬蟲的基本思路: 1)通過網(wǎng)站域名獲取 HTML 數(shù)據(jù);? ??2)解析數(shù)據(jù);? ? 3)存儲所需要的信息;? ? 4) 如有必要,移動到另一個網(wǎng)頁重復此過程。
互聯(lián)網(wǎng)工作原理——當你在瀏覽器中輸入域名按回車后,發(fā)生了什么?
你在瀏覽器輸入的域名,通過DNS服務器將URL中的域名解析為IP地址,這樣:

瀏覽器根據(jù)IP地址向web服務器發(fā)送HTTP(HyperText Transfer Protocol,超文本傳輸協(xié)議)請求,說“你給我發(fā)個網(wǎng)頁復本給這個客戶”。這個請求,具體怎么傳播的,不懂。服務器收到請求后,就同意,給瀏覽器發(fā)了一堆數(shù)據(jù)包裹(chunks,為什么拆成data chunks進行傳輸呢?為了無數(shù)用戶可以在同一時間下載同一網(wǎng)站的數(shù)據(jù)),瀏覽器收到后又把包裹裹吧裹吧成一個完整的網(wǎng)頁給傻逼客戶看。

python用urlib爬取單個網(wǎng)頁的所有信息:
from urllib.request import urlopen
#Retrieve HTML string from the URL
html = urlopen("http://www.pythonscraping.com/exercises/exercise1.html")
print(html.read())
用BeautifulSoup實現(xiàn)同樣的功能:
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj= BeautifulSoup(html.read())
print(bsObj)
要想輸出特定的數(shù)據(jù),直接.屬性就可以了。像,要輸出一級標題,直接print(bsObj.h1)

還可以實現(xiàn)一些復雜一些的功能,像,單獨把網(wǎng)頁中的特定的自定義標簽的信息抽出來,用findAll()/find():
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html, "html.parser")
nameList = bsObj.findAll("span", {"class":"green"})
for name in nameList:
print(name.get_text())
BeautifulSoup 文檔里兩者的定義:
