1、爬蟲簡介
概述
近年來,隨着網絡應用的逐漸擴展和深刻,如何有效的獲取網上數據成爲了無數公司和我的的追求,在大數據時代,誰掌握了更多的數據,誰就能夠得到更高的利益,而網絡爬蟲是其中最爲經常使用的一種從網上爬取數據的手段。
網絡爬蟲,即web spider,是一個很形象的名字。若是把互聯網比喻成一個蜘蛛網,那麼spider就是在網上爬來爬去的蜘蛛。網絡蜘蛛是經過網頁的連接地址來尋找網頁的。從網站某一個頁面開始,讀取網頁的內容,找到在網頁中的其餘連接地址,而後經過這些連接地址尋找下一個網頁,這樣一直循環下去,直到把這個網站全部的網頁都抓取完爲止。
爬蟲的價值
互聯網中最有價值的即是數據,好比天貓商城的商品信息,鏈家網的租房信息,雪球網的證券投資信息等,這些數據都表明了各個行業的真金白銀,能夠說,誰掌握了行業內的第一手數據,誰就成爲了整個行業的主宰,若是把整個互聯網的數據比喻爲一座寶藏,那咱們的爬蟲課程就是教你們如何高效地挖掘這些寶藏,掌握了爬蟲技能,你就成爲了全部互聯網信息公司幕後地老闆,換言之,它們都在免費爲你提供有價值地數據
robots.txt協議
若是本身地門戶網站中地指定頁面中地數據不想讓爬蟲程序爬取到的話,那麼能夠經過編寫一個robots.txt的協議文件來約束爬蟲程序的數據爬取。robots協議的編寫格式能夠觀察淘寶網的robots(www.taobao.com/robots.txt)。可是須要注意的是,該協議只是至關於口頭的協議,並無使用相關技術進行強制管制,因此該協議是防君子不防小人。可是咱們在學習爬蟲階段編寫的爬蟲程序能夠先忽略robots協議
爬蟲的基本流程
2、requests模塊
requests是用python語言基於urllib編寫的,採用的是Apache2 Licensed開源協議的HTTP庫,resquests它會比urllib更加方便,能夠節約咱們大量的工做。一句話,requsets是python實現最簡易用的HTTP庫,建議爬蟲使用requests庫。默認安裝號python以後,是沒有安裝requests模塊的,須要單獨經過pip安裝
2.1基本語法
requests模塊支持的請求
import requests
requests.get("http://httpbin.org/get")
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")
get請求
一、基本請求
import requests
response = requests.get('https://www.jd.com/',)
with open("jd.html","wb") as f:
f.write(response.content)
二、含參數請求
import requests
response=requests.get('https://s.taobao.com/search?q=手機')
response=requests.get('https://s.taobao.com/search',params={"q":"美女"})
三、含請求頭請求
import requests
response = requests.get('http://dig.chouti.com/',
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
}
)
四、含cookies請求
import uuid
import requests
url = 'http://httpbin.org/cookies'
cookies = dict(sbid=str(uuid.uuid4()))
res = requests.get(url,cookies=cookies)
print(res.text)
post請求
1data參數
requests.post()用法與requests.get()徹底一致,特殊的是requests.post()多了一個data參數,用來存放請求體數據
response = requests.post("http://httpbin.org/post",params={"a":"10"},data={"name":"yuan"})
2發送json數據
import requests
res1 = resquests.post(url='http://httpbin.org/post',data={'name':'yuan'})
#沒有指定請求頭,默認的請求頭:application/x-www-form-urlencoed
print(res1.json())
res2=requests.post(url='http://httpbin.org/post',json={'age':'22',})
#默認的請求頭:application/json
print(res2.json())
response對象
(1)常見屬性
import requests
response=requests.get('http://sh.lianjia.com/ershoufang/')
#response
print(response.text)
print(response.content)
print(response.status_code)
print(response.headers)
print(response.cookies)
print(response.cookies.get_dict())
print(response.cookies.items())
print(response.url)
print(response.history)
print(response.encoding)
(2)編碼問題
import requests
response = requests.get('http://www.autohome.com/news')
with open("res.html","w") as f:
f.write(response.text)
(3)下載二進制文件(圖片,視頻,音頻)
import requests
response=requests.get('http://bangimg1.dahe.cn/forum/201612/10/200447p36yk96im76vatyk.jpg')
with open("res.png","wb") as f:
for line in response.iter_content():
f.write(line)
(4)解析json數據
import requests
import json
response=requests.get('http://httpbin.org/get')
res1=json.loads(response.text)
res2=response.json()
print(res1==res2)
(5)redirection and history
默認狀況下,除了head,requests會自動處理全部重定向。可使用響應對象的history方法來追蹤重定向。response.history是一個response對象的列表,爲了完成請求而建立了這些對象。這個對象列表按照從最老到最近的請求進行排序
r = requests.get('http://github.com')
r.url
r.status_code
r.history
另外,還能夠經過allow_redirests參數禁用重定向處理:
r= requests.get('http://github.com',allow_redirects=False)
r.status_code
r.history
2.二、resquests進階用法
代理
一些網站會有相應的反爬蟲措施,例如不少網站會檢測某一段時間某個IP的訪問次數,若是訪問頻率太快以致於看起來不像正常訪客,它可能就會會禁止這個IP的訪問。因此咱們須要設置一些代理服務器,每隔一段時間換一個代理,就算IP被禁止,依然能夠換個IP繼續爬取。
res=requests.get('http://httpbin.org/ip', proxies={'http':'110.83.40.27:9999'}).json()
print(res)
2.3.爬蟲案例
import requests import re #第一步: 請求獲取token,以便經過post請求校驗 session=requests.session() res=session.get("https://github.com/login") authenticity_token=re.findall('name="authenticity_token" value="(.*?)"',res.text)[0] print(authenticity_token) # 第二步 構建post請求數據 data={ "login": "yuanchenqi0316@163.com", "password":"yuanchenqi0316", "commit": "Sign in", "utf8": "✓", "authenticity_token": authenticity_token } res=session.post("https://github.com/session",data=data,headers=headers,cookies=cookies) with open("github.html","wb") as f: f.write(res.content)