python之爬蟲(四)之 Requests庫的基本使用

什么是Requests

Requests是用python語言基于urllib編寫的,采用的是Apache2 Licensed開源協議的HTTP庫
如果你看過上篇文章關于urllib庫的使用,你會發現,其實urllib還是非常不方便的,而Requests它會比urllib更加方便,可以節約我們大量的工作。(用了requests之后,你基本都不愿意用urllib了)一句話,requests是python實現的最簡單易用的HTTP庫,建議爬蟲使用requests庫。

默認安裝好python之后,是沒有安裝requests模塊的,需要單獨通過pip安裝

requests功能詳解

總體功能的一個演示

import requestsresponse  = requests.get("https://www.baidu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
print(response.content)
print(response.content.decode("utf-8"))
View Code

我們可以看出response使用起來確實非常方便,這里有個問題需要注意一下:
很多情況下的網站如果直接response.text會出現亂碼的問題,所以這個使用response.content
這樣返回的數據格式其實是二進制格式,然后通過decode()轉換為utf-8,這樣就解決了通過response.text直接返回顯示亂碼的問題.

請求發出后,Requests 會基于 HTTP 頭部對響應的編碼作出有根據的推測。當你訪問 response.text 之時,Requests 會使用其推測的文本編碼。你可以找出 Requests 使用了什么編碼,并且能夠使用 response.encoding 屬性來改變它.如:

response =requests.get("http://www.baidu.com")
response.encoding="utf-8"
print(response.text)

不管是通過response.content.decode("utf-8)的方式還是通過response.encoding="utf-8"的方式都可以避免亂碼的問題發生

各種請求方式

requests里提供個各種請求方式

import requests
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 requestsresponse = requests.get('http://httpbin.org/get')
print(response.text)

帶參數的GET請求,例子1

import requestsresponse = requests.get("http://httpbin.org/get?name=zhaofan&age=23")
print(response.text)

如果我們想要在URL查詢字符串傳遞數據,通常我們會通過httpbin.org/get?key=val方式傳遞。Requests模塊允許使用params關鍵字傳遞參數,以一個字典來傳遞這些參數,例子如下:

import requests
data = {"name":"zhaofan","age":22
}
response = requests.get("http://httpbin.org/get",params=data)
print(response.url)
print(response.text)

上述兩種的結果是相同的,通過params參數傳遞一個字典內容,從而直接構造url
注意:第二種方式通過字典的方式的時候,如果字典中的參數為None則不會添加到url上

解析json

import requests
import jsonresponse = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json()))

從結果可以看出requests里面集成的json其實就是執行了json.loads()方法,兩者的結果是一樣的

獲取二進制數據

在上面提到了response.content,這樣獲取的數據是二進制數據,同樣的這個方法也可以用于下載圖片以及
視頻資源

添加headers
和前面我們將urllib模塊的時候一樣,我們同樣可以定制headers的信息,如當我們直接通過requests請求知乎網站的時候,默認是無法訪問的

import requests
response =requests.get("https://www.zhihu.com")
print(response.text)

這樣會得到如下的錯誤

因為訪問知乎需要頭部信息,這個時候我們在谷歌瀏覽器里輸入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)

這樣就可以正常的訪問知乎了

基本POST請求

通過在發送post請求時添加一個data參數,這個data參數可以通過字典構造成,這樣
對于發送post請求就非常方便

import requestsdata = {"name":"zhaofan","age":23
}
response = requests.post("http://httpbin.org/post",data=data)
print(response.text)

同樣的在發送post請求的時候也可以和發送get請求一樣通過headers參數傳遞一個字典類型的數據

響應

我們可以通過response獲得很多屬性,例子如下

import requestsresponse = requests.get("http://www.baidu.com")
print(type(response.status_code),response.status_code)
print(type(response.headers),response.headers)
print(type(response.cookies),response.cookies)
print(type(response.url),response.url)
print(type(response.history),response.history)

結果如下:

狀態碼判斷
Requests還附帶了一個內置的狀態碼查詢對象
主要有如下內容:

100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '?'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),

Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0

Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),

Server Error.
500: ('internal_server_error', 'server_error', '/o\', '?'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),

通過下面例子測試:(不過通常還是通過狀態碼判斷更方便)

import requestsresponse= requests.get("http://www.baidu.com")
if response.status_code == requests.codes.ok:print("訪問成功")

requests高級用法

文件上傳

實現方法和其他參數類似,也是構造一個字典然后通過files參數傳遞

import requests
files= {"files":open("git.jpeg","rb")}
response = requests.post("http://httpbin.org/post",files=files)
print(response.text)

結果如下:

獲取cookie

import requestsresponse = requests.get("http://www.baidu.com")
print(response.cookies)for key,value in response.cookies.items():print(key+"="+value)

會話維持

cookie的一個作用就是可以用于模擬登陸,做會話維持

import requests
s = requests.Session()
s.get("http://httpbin.org/cookies/set/number/123456")
response = s.get("http://httpbin.org/cookies")
print(response.text)

這是正確的寫法,而下面的寫法則是錯誤的

import requestsrequests.get("http://httpbin.org/cookies/set/number/123456")
response = requests.get("http://httpbin.org/cookies")
print(response.text)

因為這種方式是兩次requests請求之間是獨立的,而第一次則是通過創建一個session對象,兩次請求都通過這個對象訪問

證書驗證

現在的很多網站都是https的方式訪問,所以這個時候就涉及到證書的問題

import requestsresponse = requests.get("https:/www.12306.cn")
print(response.status_code)

默認的12306網站的證書是不合法的,這樣就會提示如下錯誤

為了避免這種情況的發生可以通過verify=False
但是這樣是可以訪問到頁面,但是會提示:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See:?https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings?InsecureRequestWarning)

解決方法為:

import requests
from requests.packages import urllib3
urllib3.disable_warnings()
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)

這樣就不會提示警告信息,當然也可以通過cert參數放入證書路徑

代理設置

import requestsproxies= {"http":"http://127.0.0.1:9999","https":"http://127.0.0.1:8888"
}
response  = requests.get("https://www.baidu.com",proxies=proxies)
print(response.text)

如果代理需要設置賬戶名和密碼,只需要將字典更改為如下:
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}
如果你的代理是通過sokces這種方式則需要pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}

超時設置

通過timeout參數可以設置超時的時間

認證設置

如果碰到需要認證的網站可以通過requests.auth模塊實現

import requestsfrom requests.auth import HTTPBasicAuthresponse = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
print(response.status_code)

當然這里還有一種方式

import requestsresponse = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)

異常處理

關于reqeusts的異常在這里可以看到詳細內容:
http://www.python-requests.org/en/master/api/#exceptions
所有的異常都是在requests.excepitons中

?

?

從源碼我們可以看出RequestException繼承IOError,
HTTPError,ConnectionError,Timeout繼承RequestionException
ProxyError,SSLError繼承ConnectionError
ReadTimeout繼承Timeout異常
這里列舉了一些常用的異常繼承關系,詳細的可以看:
http://cn.python-requests.org/zh_CN/latest/_modules/requests/exceptions.html#RequestException

通過下面的例子進行簡單的演示

import requestsfrom requests.exceptions import ReadTimeout,ConnectionError,RequestExceptiontry:response = requests.get("http://httpbin.org/get",timout=0.1)print(response.status_code)
except ReadTimeout:print("timeout")
except ConnectionError:print("connection Error")
except RequestException:print("error")

其實最后測試可以發現,首先被捕捉的異常是timeout,當把網絡斷掉的haul就會捕捉到ConnectionError,如果前面異常都沒有捕捉到,最后也可以通過RequestExctption捕捉到

轉載于:https://www.cnblogs.com/shuai1991/p/10814937.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/277789.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/277789.shtml
英文地址,請注明出處:http://en.pswp.cn/news/277789.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

https://blog.csdn.net/cscscscsc/article/details/50

https://blog.csdn.net/cscscscsc/article/details/50899522轉載于:https://blog.51cto.com/7237876/2129682

linux下安裝mysql說明

1.msyql下載 mysql-5.6.33 通用版,linux64位,官方下載地址:http://dev.mysql.com/downloads/mysql/5.6.html#downloads。也可以通過命令下載:wget http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.33-linux-glibc2.5-x86…

win8下cocos2dx-3.2+VS2012環境配置及項目創建

這是本人CSDN的第一篇博客,因為假期在學校做實訓項目接觸到了cocos2dx,覺得是一個特別適用強大,有不錯的可移植性(雖然可移植性不錯,但實際上寫好的游戲往Android上移植,我的隊友廢了好大勁。。。&#xff…

Android通過透明度設置背景變暗

變暗 WindowManager.LayoutParams lpgetWindow().getAttributes(); lp.alpha0.3f; getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); getWindow().setAttributes(lp);變為原來的樣子 WindowManager.LayoutParams lpgetWindow().getAttributes(); lp.alpha1.…

BZOJ4557:[JLOI2016/SHOI2016]偵察守衛——題解

https://www.lydsy.com/JudgeOnline/problem.php?id4557 小R和B神正在玩一款游戲。這款游戲的地圖由N個點和N-1條無向邊組成,每條無向邊連接兩個點,且地圖是連通的。換句話說,游戲的地圖是一棵有N個節點的樹。 游戲中有一種道具叫做偵查守衛…

Mac系統下Homebrew的安裝和使用Homebrew安裝python

這里向大家推薦一個東西,Mac下很好用的東西,叫做Homebrew。剛開始接觸Mac的時候,我也沒聽過這個東西,但裝了以后真的覺得,TMD太碉堡了。引用一句話:Homebrew is the easiest and most flexible way to inst…

JS中的深拷貝

前言:我們經常會遇到想要將一個對象為己所用,但又不能污染原對象的需求,這就涉及到了js對象的深拷貝。 比如說在VUE的子組件中,父組件傳過來的數據中若是有對象,而子組件需要用父組件的數據進行初始化并且有另做他用的…

Mac下cocos2dx-3.2+Xcode環境配置和項目創建

這是有關環境配置的第二篇教程,第一篇講的是win8下的環境配置。這里我們使用C。所有如果你用其他語言如Lua和js進行cocos2d開發,那么可以再找一找其他的配置文檔。下面要說Mac os 下 cocos2dx-3.2Xcode的環境配置,這里我使用的是Xcode 5.1.1。…

對flex-grow和flex-shrink的深入理解

flex彈性布局,如果子元素寬度之和大于或者小于父元素寬度,空間就會存在剩余和不夠,flex默認不換行,除非設置flex-wrap,那么這種情況下,有兩個重要的屬性,flex-grow和flex-shrink. flex-grow默認值為0&#…

拿下京東榜單第五首戰告捷,看聯想手機如何上演王者歸來

618對于手機行業來說是一個非常重要的日子,京東618上銷量的高低在某種程度上就代表了該手機品牌在國內市場的影響力,以及在行業中所處的位置。因此,今年的618各大手機品牌卯足了勁在京東平臺上展開較量。榮耀、小米、VIVO、OPPO等手機品牌相繼…

Mac OS使用技巧之一:查看Finder中的.bash_profile等系統隱藏文件

作為一個程序員,經常要配置變量,可能要更改hosts文件,或者你閑著沒事兒尋找homebrew給你安裝的東西在什么地方。Mac OS的內核是Unix,Linux/Unix系統出于系統安全和用戶安全的考慮,會把一些與系統相關的文件隱藏&#x…

java.lang.NumberFormatException: For input string: “name”

背景&#xff1a;action中查詢出list數據需要在前臺進行顯示&#xff0c;但根據主鍵在數據庫中查詢出的數據list中含有熟悉alist屬性為配置表&#xff0c;且支持用戶多選&#xff0c;前端通過el表達式顯示 前臺界面為&#xff1a;<c:forEach items"${list}" var&q…

win8下cocos2dx3.2移植android平臺及代碼打包APK

cocos2dx程序不能只在VS2012下運行&#xff0c;遲早是要搬運到Android和IOS上的。Windows下移植IOS平臺先擱下不說比較困難&#xff0c;而且只有越獄的蘋果機才可以運行&#xff0c;而且畢竟IOS高端、小眾。這里主要講一下移植Android&#xff0c;windows下cocos2dx打包成APK和…

【轉】用Fiddler做抓包分析詳解

1.為什么是Fiddler? 抓包工具有很多&#xff0c;小到最常用的web調試工具firebug&#xff0c;達到通用的強大的抓包工具wireshark.為什么使用fiddler?原因如下&#xff1a; a.Firebug雖然可以抓包&#xff0c;但是對于分析http請求的詳細信息&#xff0c;不夠強大。模擬http…

讀《活著》----余華

這本書所處時代背景盡管與我生活的時代背景不同&#xff0c;但是我仍是被人物的生活所打動。這本書為我們描述了一個擁有一百畝的闊少爺徐福貴因為賭而輸掉全部家產&#xff0c;到經歷將自己的父親&#xff0c;母親&#xff0c;兒子&#xff0c;女兒&#xff0c;女媳&#xff0…

常用數據庫連接和diriver以及默認端口

sqlserver默認端口號為&#xff1a;1433 URL:"jdbc:microsoft:sqlserver://localhost:1433;DatabaseNamedbname" DRIVERNAME:"com.microsoft.jdbc.sqlserver.SQLServerDriver"; mysql 默認端口號為&#xff1a;3306 URL:jdbc:mysql://localhost:3306/…

Mac下cocos2dx3.2移植android平臺詳細教程

本文是cocos2dx移植android的第二篇教程&#xff0c;筆者深深感覺&#xff0c;cocos2dx移植android平臺是永遠的痛啊。。。下面講一下筆者花費一個周研究的Mac OS下的cocos2dx3.2android配置首先要準備的東西&#xff08;1&#xff09;下載cocos2dx3.2 http://www.cocos2d-x.o…

robotframework(12)修改用戶密碼(從數據庫查詢短信驗證碼)

一、testcase&#xff1a;修改用戶密碼需要6個參數&#xff08;短信驗證碼、設置的新密碼、用戶已登錄的userid及用戶唯一標識、接口校驗碼、被修改的手機號&#xff09;&#xff0c;故先準備這些參數 二、用戶登錄請求&#xff0c;&#xff08;獲取userid、用戶唯一標識&#…

Mac OS使用技巧之二:修改變量Path解決android: command not found

前一陣子&#xff0c;一直在搞Mac OS和win8下cocos2dx移植android平臺的方法。一步步從無到有的慢慢摸索出來。最近發現了一個小問題&#xff0c;有關環境變量配置的寫下來分享給大家。就是我們在windows8下查看已有android SDK的版本&#xff0c;需要在CMD里面輸入&#xff1a…

Jenkins架構

一. Master 和slave.下圖闡述了master-slave交互的架構&#xff1a;在上面這個分布式的構建環境中&#xff0c;Jenkins master主要負責如下&#xff1a;接收構建觸發&#xff08;比如&#xff0c;一個提交到GitHub后&#xff09;發送通知&#xff08;比如&#xff0c;在構建失敗…