Requests庫基礎入門

1.Requests庫入門

中文文檔:https://requests.readthedocs.io/zh_CN/latest/
gittub地址:https://github.com/requests/requests
更多信息在 http://www.python-requests.org

Requests庫的7個主要方法

方法 說明
requests.requests(method,url,**kwargs) 構造一個請求,支撐一下各方法的基礎方法
requests.get(url,params=None,**kwargs) 獲取一個HTML頁面的信息;對應於HTTP的GET;
requests.head(url,**kwargs) 獲取HTML網頁的頭部信息;對應於HTTP的HEAD
requests.put(url,data=None,**kwargs) 向HTML網頁提交PUT(全局修改)請求;對應於HTTP的PUT;(根據提交內容的不同,自動存儲信息爲form形式或者data形式)
requests.patch(url,data=None,**kwargs) 向HTML網頁提交局部修改請求;對應於HTTP的PATCH;
requests.delete(url,**kwargs) 向HTML網頁提交刪除請求;對應於HTTP的DELETE;
import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
r.encoding='utf-8'
print(r.text)

1.1get()方法

最簡單的代碼就是

r=requests.get(url)

完整代碼就是

 requests.get(url,params=None,**kwargs)
  1. URL:全稱爲Uniform Resource Locator統一資源定位符,包含了協議,服務器名稱,路徑和文件名等信息。

  2. API:全稱爲application programming interface;應用程序編程接口;

  3. params:字典或字符串格式作爲參數增加到url中,是額外參數。

  4. **kwargs:代表十二個控制訪問的參數;
    (1)data:字典,字符串或文件對象,作爲Request對象的內容;
    (2)json: JSON格式的數據作爲Request對象的內容;
    (3)headers:字典,HTTP頭部信息;目的是將請求僞裝成諸如瀏覽器,使用post方法向服務器發起訪問;
    (4)cookies:字典或者CookieJar,Request中的cookie;
    (5) auth:元組,支持HTTP認證功能;
    (6)files: 字典類型,向服務器傳輸文件;
    (7)timeout: 設定超時時間,單位秒;
    (8)proxies:字典類型,設定訪問代理服務器,可以增加登錄認證;
    (9) allow_redirects:True/False,默認爲True,重定向開關; //高級功能使用
    (10)stream: 布爾值,默認爲真,獲取內容立即下載開關;//高級功能使用
    (11)verify:布爾值,默認爲真,認證SSL證書開關; //高級功能使用
    (12)cert:保存本地SSL證書路徑; //高級功能使用
    13個參數通過賦值的方法來調用
    在這裏插入圖片描述
    使用get函數會內部生成一個Request對象,以及一個Response對象(也就是 r );
    Response對象包含了Request對象發送的全部信息以及爬蟲返回的全部內容

1.1.2對於Response對象

import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
r.encoding='utf-8'
print(r.text)

#返回r的類
print(type(r))
# <class 'requests.models.Response'>

#返回的頭部信息
print(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, 04 Feb 2020 17:24:26 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

1.1.2Response對象的屬性

屬性 說明
r.status_code HTTP請求返回的狀態,200表示成功,404和其他表示失敗;
r.text 響應內容的字符串形式;即url對應的頁面內容
r.encoding 從響應內容的頭部信息猜測響應內容的編碼方式
r.apparent_encoding 從響應內容的內容信息分析響應內容的編碼方式;(備選編碼方式)
r.content 將爬取到的響應內容的二進制形式還原成響應內容;

Response對象提供了一個單獨的方法raise_for_status()方法

r.raise_for_status() HTTP的請求返回狀態不是200則產生 request.HTTPError;
  • 基本流程
    在這裏插入圖片描述
    在這裏插入圖片描述
    apparent_encoding是實實在在根據文本內容得出編碼,比encoding更加準確,得到的文本內容更會是所需要的
import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
#200
print(r.text)
# <!DOCTYPE html>
# <!--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>
print(r.encoding)# ISO-8859-1

print(r.apparent_encoding)#utf-8

r.encoding='utf-8'
print(r.text)#出現中文字符
# <!DOCTYPE html>
# <!--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>
#
# <class 'requests.models.Response'>
# {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Wed, 05 Feb 2020 15:34:33 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

1.2爬取網頁的通用代碼框架

網絡連接有風險,顧異常處理很重要

1.2.1 Requests庫的常見異常

異常 說明
requests.ConnectionError 網絡連接錯誤異常,如DNS查詢失敗,拒絕連接等;
requests.HTTPError HTTP錯誤異常
requests.URLRequired URL缺失異常
requests.TooManyRedirects 超過最大重定向次數,產生重定向異常;對複雜連接訪問常常出現的錯誤
requests.ConnectTimeout 連接遠程服務器超時異常;
requests.Timeout 請求URL超時,產生超時異常;

requests.Timeout指整個過程超時,而requests.ConnectTimeout僅僅指鏈接遠程服務器超時異常

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 "WRONG!"
if __name__=="__main__":
    url="http://www.baidu.com"
    print(getHTMLText(url))

1.3HTTP協議及Requests庫方法

HTTP協議:Hypertext Transfer Protocol 超文本傳輸協議;是一個基於“請求與響應”模式的,無狀態的(非時序)應用層協議;即用戶發起請求,服務器發出相應響應,無狀態表示第一次訪問與第二次訪問無實質性聯繫

HTTP協議採用URL作爲定位網絡資源的標識
在這裏插入圖片描述
URL就是通過HTTP協議存取資源的internet路徑,一個URL對應一個數據資源
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
PATCH的最主要好處就是節省 網絡帶寬

1.1.4Requests庫主要方法解析

params:字典或字符串格式作爲參數增加到url中,是額外參數。

import requests
#params
kv={'key':'value1','key2':'value2'}
r=requests.request('GET','http://python123.io/ws',params=kv)
print(r.url)
#https://python123.io/ws?key=value1&key2=value2

**kwargs:代表十二個控制訪問的參數;
(1)data:字典,字符串或文件對象,作爲Request對象的內容;
(2)json: JSON格式的數據作爲Request對象的內容;
(3)headers:字典,HTTP頭部信息;目的是將請求僞裝成諸如瀏覽器,使用post方法向服務器發起訪問;
(4)cookies:字典或者CookieJar,Request中的cookie;
(5) auth:元組,支持HTTP認證功能;
(6)files: 字典類型,向服務器傳輸文件;
(7)timeout: 設定超時時間,單位秒;
(8)proxies:字典類型,設定訪問代理服務器,可以增加登錄認證;
(9) allow_redirects:True/False,默認爲True,重定向開關; //高級功能使用
(10)stream: 布爾值,默認爲真,獲取內容立即下載開關;//高級功能使用
(11)verify:布爾值,默認爲真,認證SSL證書開關; //高級功能使用
(12)cert:保存本地SSL證書路徑; //高級功能使用

import requests
#params
kv={'key':'value1','key2':'value2'}
r=requests.request('GET','http://python123.io/ws',params=kv)
print(r.url)
#https://python123.io/ws?key=value1&key2=value2

#headers:字典,HTTP定製頭
hd={'user-agent':'Chrome/10'}#Chrome瀏覽器的第十個版本
r=requests.request('POST','http://python123.io/ws',headers=hd)

#fs
fs={'file':open('data.xls','rb')}
r=requests.request('POST','http://python123.io/ws',file=fs)

#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)
#訪問地址時就是使用代理服務器的地址,有效的防止反追蹤
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章