#沒有誰天生喜歡學習,只是不願輸#
(初學爬蟲,會持續更新)
①爬取工具:MySQL數據庫
Navicat for mysql
編程語言python3
集成開發環境pycharm(community)
Python包管理器Anaconda3
②基本知識:(1)request庫:
requests庫的七個主要方法
requests.request() ==> 構造一個請求,支撐以下各方法的基礎方法
requests.get() ==> 獲取HTML網頁的主要方法,對應於HTTP的GET
requests.head() ==> 獲取HTML網頁頭信息的方法,對應於HTTP的HEAD
requests.post() ==> 向HTML網頁提交POST請求的方法,對應於HTTP的POST
requests.put() ==> 向HTML網頁提交PUT請求的方法,對應於HTTP的PUT
requests.patch() ==> 向HTML網頁提交局部修改請求,對應於HTTP的PATCH
requests.delete() ==> 向HTML頁面提交刪除請求,對應於HTTP的DELETE
Requests庫的兩個重要對象分別是Response和Request
其中Response對象包含爬蟲返回的全部信息
Response對象的屬性
r.status_code ==> HTTP請求的返回狀態,200表示連接成功,404表示連接失敗
r.text ==> HTTP響應內容的字符串形式,即,url對應的頁面內容
r.encoding ==> 從HTTP header中猜測的響應內容編碼方式
r.apparent_encoding ==> 從內容中分析出的響應內容編碼方式(備選編碼方式)
r.content ==> HTTP響應內容的二進制形式
Response的編碼
Requests庫的異常
requests.ConnectionError ==> 網絡連接錯誤異常,如DNS查詢失敗、拒絕連接等
requests.HTTPError ==> HTTP錯誤異常
requests.URLRequired ==> URL缺失異常
requests.TooManyRedirects ==> 超過最大重定向次數,產生重定向異常
requests.ConnectTimeout ==> 連接遠程服務器超時異常
requests.Timeout ==> 請求URL超時,產生超時異常
爬取網頁的通用代碼框架
import requests def getHTMLText(url): try: r=requests.get(url,timeout=30) r.raise_for_status() #如果狀態不是200,引發HTTPError異常 r.encoding=r.apparent_encodinng return r.text except: return "產生異常" if _name_ == "_main_": url="http://www.baidu.com" print(getHTMLText(url))
Requests函數包括十三個訪問控制參數
requests.request(method,url,**kwargs)
**kwargs: 控制訪問的參數,均為可選項
①params: 字典或字節序列,作為參數增加到url中
>>>kv={'key1':'value1','key2':'value2'} >>>r=requests.request('GET','http://python123.io/ws',params=kv) >>>print(r,url) http://python123.io/ws?key1=value1&key2=value2
②data: 字典、字節序列或文件對象,作為Request的內容
>>>kv=('key1':'value1','key2':'value2') >>>r=requests.request('POST','http://python123.io/ws',data=kv) >>>body='主體內容' >>>r=requests.request('POST','http://python123.io/ws',data=body)
③json: JSON格式的數據,作為Request的內容
>>>kv={'key1':'value1'} >>>r=requests.request('POST','http://python123.io/ws',json=kv)
④headers: 字典,HTTP定制頭
>>>hd={'user-agent';'Chrome/10'} >>>r=requests.request('POST','http://python123.io/ws',headers=hd)
⑤cookies(是request庫的高級功能): 字典或Cookie.Jar , Request中的cookie
⑥auth(是request庫的高級功能): 元組, 支持HTTP認證功能
⑦files: 字典類型,傳輸文件
>>>fs={'file': open('data.xls','rb')} >>>r=requests.request('POST','http://python123.io/ws',files=fs)
⑧timeout: 設定超時時間,秒為單位
>>>r=requests.request('GET','http://www.baidu.com',timeout=10)
⑨proxies: 字典類型,設定訪問代理服務器,可以增加登錄認證
>>>pxs={'http':'http://user:pass@10.10.1:1234' 'https':'https://10.10.10.1:4321'} >>>r=requests.request('GET','http://www.baidu.com',proxies=pxs)
⑩allow_redirects: True/False,默認為True,重定向開關
⑪stream: True/False,默認為True,獲取內容立即下載開關
⑫verify: True/False,默認為True,認證SSL證書開關
⑬cert: 本地SSL證書路徑
Requests庫網絡爬取簡單實例
①百度360搜索關鍵詞提交:
搜索引擎關鍵詞提交接口:
百度的關鍵詞接口:http://www.baidu.com/s?wd=keyword
360的關鍵詞接口:http://www.so.com/s?q=keyword
百度搜索全代碼:
import requests keyword="Python" try: kv={'wd':keyword} r=requests.get("http://www.baidu.com/s" , params=kv) print(r.request.url) r.raise_for_status() print(len(r.text)) except: print("爬取失敗")
360搜索全代碼:
import requests keyword="Python" try: kv={'q':keyword} r=requests.get(http://www.so.com/s , params=kv) print(r.request.url) r.raise_for_status() print(len(r.text)) except: print("爬取失敗")
②網絡圖片的爬取和存儲:
網絡圖片鏈接的格式:
http://www.example.com/picture.jpg
圖片爬取全代碼:
import requests import os url="http://image.ngchina.com.cn/2019/0707/20190707123014213.jpg" root="D://pictures//" path=root+url.split('/')[-1] try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r=requests.get(url) with open(path,'wb') as f: f.write(r.content) f.close() print("文件保存成功") else: print("文件已存在") except: print("爬取失敗")
③IP地址歸屬地的自動查詢:
IP地址查詢的全代碼:
import requests url="http://m.ip138.com/ip.asp?ip=" try: r=requests.get(url+'202.204.80.112') r.raise_for_status() r.encoding=r.apparent_encoding print(r.text[-500:]) except: print("爬取失敗")
-
④添加headers:
-
和前面我們將urllib模塊的時候一樣,我們同樣可以定制headers的信息,如當我們直接通過requests請求知乎網站的時候,默認是無法訪問的,會得到如下錯誤:
因為訪問知乎需要頭部信息,這個時候我們在谷歌瀏覽器里輸入chrome://version,就可以看到用戶代理,將用戶代理添加到頭部信息
import requests headers = { "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" } response =requests.get("https://www.zhihu.com",headers=headers) print(response.text)