1. 程式人生 > >python—網絡爬蟲(1)

python—網絡爬蟲(1)

lock max styles 更多 64 bit man nsf 理解 網址

安裝 request庫
1,運行裏面輸入 CMD 直接輸入 pip install requests回車,即可安裝
2,直接在終端輸入python進入python自帶的IDLE
3,下面命令即爬取百度頁面信息內容

C:\Users\ftsdata-02>python #輸入python進入IDLE
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests #導入requests庫
>>> r = requests.get("http://www.baidu.com") #用requests庫裏面的get方法獲取百度網址內容信息
>>> r #查看獲取返回信息值, 200表示獲取成功
<Response [200]>
>>> r.status_code #運用status_code也可查看獲取網頁是否成功,顯示200,即成功獲取
200
>>> r.encoding=‘utf-8‘ #將獲取的百度網頁字符碼轉換成utf-8字符編碼
>>> r.text #顯示爬出網頁內容
‘<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class="head_wrapper"> <div class="s_form"> <div class="s_form_wrapper"> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class="fm"> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class="s_ipt" value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class="mnav">新聞</a> <a href=http://www.hao123.com name=tj_trhao123 class="mnav">hao123</a> <a href=http://map.baidu.com name=tj_trmap class="mnav">地圖</a> <a href=http://v.baidu.com name=tj_trvideo class="mnav">視頻</a> <a href=http://tieba.baidu.com name=tj_trtieba class="mnav">貼吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class="lb">登錄</a> </noscript> <script>document.write(\‘<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\‘+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \‘" name="tj_login" class="lb">登錄</a>\‘);</script> <a href=//www.baidu.com/more/ name=tj_briicon class="bri" style="display: block;">更多產品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>關於百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必讀</a>&nbsp; <a href=http://jianyi.baidu.com/ class="cp-feedback">意見反饋</a>&nbsp;京ICP證030173號&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n‘

總結:
requests 庫的7個主要方法:
requests.request() 構造一個請求,支撐以下各方法的基礎方法

requests.request(method, url, **kwargs)
method:請求方式,對應get/put/post等七種
url:擬獲取頁面的url鏈接
**kwargs:控制訪問的參數共13個。
requests.request(‘GET‘, url, **kwargs)
requests.request(‘HEAD‘, url, **kwargs)
requests.request(‘POST‘, url, **kwargs)
requests.request(‘PUT‘, url, **kwargs)
requests.request(‘PATCH‘, url, **kwargs)
requests.request(‘DELETE‘, url, **kwargs)
requests.request(‘OPTIONS‘, 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:字典或CookieJar, Request中的cookie
auth:元組,支持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:[email protected]: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,獲取內容立即下載開關
varify:  True/False,默認為True,認證SSL證書開關
cert:本地SSL證書路徑


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


r = requests.get(url) 構造一個向服務器請求資源的Request對象 Request,並且返回一個包含服務器資源的Response對象;
requests.get(url, params = None, **kwargs)
url: 擬獲取頁面的url鏈接
params: url中額外參數,字典或字節流格式,可選**kwargs: 12個控制訪問的參數

Requests庫的2個重要的對象
Request 和 Response對象

Response對象包含爬蟲返回的所有內容
>>> import requests #導入requests庫
>>> r = requests.get("http://www.baidu.com")
>>> print(r.status_code)
200
>>> type(r)
<class ‘requests.models.Response‘>
>>> r.headers
{‘Cache-Control‘: ‘private, no-cache, no-store, proxy-revalidate, no-transform‘, ‘Connection‘: ‘Keep-Alive‘, ‘Content-Encoding‘: ‘gzip‘, ‘Content-Type‘: ‘text/html‘, ‘Date‘: ‘Tue, 05 Jun 2018 11:48:31 GMT‘, ‘Last-Modified‘: ‘Mon, 23 Jan 2017 13:27:36 GMT‘, ‘Pragma‘: ‘no-cache‘, ‘Server‘: ‘bfe/1.0.8.18‘, ‘Set-Cookie‘: ‘BDORZ=27315; max-age=86400; domain=.baidu.com; path=/‘, ‘Transfer-Encoding‘: ‘chunked‘}
>>>

Response對象的屬性:
r.status_code HTTP請求的返回狀態,200表求連接成功,404表示失敗
r.text HTTP響應內容的字符串形式,即,url對應的頁面內容
r.encoding 從HTTP header中猜測的響應內容編碼方式
r.apparent_encoding 從內容中分析出的響應內容編碼方式(備選編碼方式)
r.content HTTP響應內容的二進制形式

>>> r.apparent_encoding
‘utf-8‘
>>> r.encoding=‘utf-8‘
>>> r.test

理解Response的編碼
r.encoding 從HTTP header中猜測的響應內容編碼方式
r.apparent_encoding 從內容中分析出的響應內容編碼方式(備選編碼方式)
r.encoding:如果header中不存在charset,則認為編碼為ISO-88591
r.apparent_encoding: 根據網頁內容分析出的編碼方式

理解Requests庫的異常
requests.ConnectionError 網絡連接錯誤異常,如DNS查詢失敗,拒絕連接等
requests.HTTPError HTTP錯誤異常
requests.URLRequired URL缺失異常
requests.TooManyRedirects 超過最大重定向次數,產生重定向異常
requests.ConnectTimeout 連接遠程服務器超時異常
requests.Timeout 請求URL超時,產生的異常

r.raise_for_status() 如果不是200,產生異常requests.HTTPError

>>> import requests
>>> def getHTMLText(url):
... try:
... r=requests.get(url,timeout=30)
... r.raise_for_status()
... r.encoding=r.apparent_encoding
... return r.text
... except:
... return
...
>>> if __name__==‘__main__‘:
... url="http://www.baidu.com"
... print(getHTMLText(url))

HTTP協議:超文本傳輸協議。
HTTP是一個基於“請求與響應”模式的、無狀態的應用層協議。
HTTP協議采用URL作為定位網絡資源的標識。
URL格式: http://host[:port][path]
host: 合法的Internet主機域名或IP地址
port: 端口號,缺省端口為80
path: 請求資源路徑

URL是通過HTTP協議存取資源的Internet路徑,一個URL對應一個數據資源。

HTTP協議對資源的操作:
GET     請求獲取URL位置的資源
HEAD    請求URL位置資源的響應消息報告,即獲得該資源的頭部信息
POST    請求向URL位置的資源後附加新的數據
PUT     請求向URL位置存儲一個資源,覆蓋原URL位置的資源
PATCH   請求局部更新URL位置的資源,即該處資源的部分內容
DELETE   請求刪除URL位置存儲的資源

理解PATCH與PUT的區別
假設URL位置有一組數據UserInfo,包括UserID,UserName等等20個字段。
需求:用戶修改了UserName,其他的不變。
采用PATCH,僅向URL提交UserName的局部更新請求。
采用PUT,必須將所有20個字段一並提交到URL,未提交字段被刪除。

PATCH最大的優點:節省網絡帶寬

Requests庫的post()方法
下示例:向URL POST一個字典,自動編碼為form(表單)
>>> payload={‘key1‘:‘value1‘,‘key2‘:‘value2‘}
>>> r=requests.post(‘http://httpbin.org/post‘,data=payload)
>>> print(r.text)
{...
"form":{
"key2":"value2",
"key1":"value1
},
}

Requests庫的put()方法
>>> payload={‘key1‘:‘value1‘, ‘key2‘:‘value2‘}
>>> r=requests.put(‘http://httpbin.org/put‘,data=payload)
>>> print(r.text)
{
...
"form":{
"key2":"value2",
"key1":"value1"
},
}

python—網絡爬蟲(1)