1 準備
安裝scrapy:css
國內鏡像源(官方的pypi不穩定)安裝 pip3 install -i https://pypi.douban.com/simple/ scrapy
安裝virtualenvwrapper:node
下載 pip3 install virtualenvwrapper 建立目錄存放虛擬環境 mkdir ~/.virtualenvs 配置環境變量 export WORKON_HOME=~/.virtualenvs source /usr/local/python3/bin/virtualenvwrapper.sh source ~/.bashrc
2 技術選擇與實現(scrapy vs reqeust + beautifulsoup)
不是一個層級的使用python
requests + beautifulsoup 是庫 scrapy 是框架
性能web
在網絡請求方面: scrapy 基於twisted實現,具備高性能優點 --- 異步IO ; 在數據處理方面: scrapy方便擴展,不少內置功能;內置 css,xpath選擇器selector很是方便;lxml是c寫的 因此更快 而beautifulsoup 是 python寫的,會慢一點
3 爬蟲的應用
1 .搜索引擎 --- 百度,goole(全部互聯網的信息) ,垂直領域的搜索引擎(汽車,娛樂信息) 2 推薦引擎 --- 今日頭條,數據推送 3 機器學習的樣本 4 數據分析 ---金融,輿情分析
4 網頁分類
靜態網頁 --- 相似靜態博客系統,沒有數據庫操做 動態網頁 --- 淘寶,信息更新(動態加載) webservice(restapi) ajax + rest api
5 爬蟲的經常使用策略
網站的 url 鏈接通常是 樹形的結構(分層結構,不一樣的路由),並且網站的url 多是環路,須要去重ajax
(1)深度優先算法 和 實現 (scrapy默認使用)算法
遞歸實現 def depth_tree(tree_node): if tree_node is not None: if tree_node._left is not None: return depth_tree(tree_node._left) if tree_node._right is not None: return depth_tree(tree_node._right) 遞歸層數太多---會有棧溢出的問題
(2)廣度優先算法 和 實現數據庫
隊列實現 def level_queue(root): if root is None: return my_queue = [] node =root my_queue.append(node) while my_queue: node = my_queue.pop(0) if node.lchild is not None: my_queue.append(node.lchild) if node.rchild is not None: my_queue.append(node.rchild)