日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python之爬虫(四)之 Requests库的基本使用

發(fā)布時(shí)間:2023/12/9 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python之爬虫(四)之 Requests库的基本使用 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

什么是Requests

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

默認(rèn)安裝好python之后,是沒有安裝requests模塊的,需要單獨(dú)通過pip安裝

requests功能詳解

總體功能的一個(gè)演示

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使用起來確實(shí)非常方便,這里有個(gè)問題需要注意一下:
很多情況下的網(wǎng)站如果直接response.text會(huì)出現(xiàn)亂碼的問題,所以這個(gè)使用response.content
這樣返回的數(shù)據(jù)格式其實(shí)是二進(jìn)制格式,然后通過decode()轉(zhuǎn)換為utf-8,這樣就解決了通過response.text直接返回顯示亂碼的問題.

請(qǐng)求發(fā)出后,Requests 會(huì)基于 HTTP 頭部對(duì)響應(yīng)的編碼作出有根據(jù)的推測。當(dāng)你訪問 response.text 之時(shí),Requests 會(huì)使用其推測的文本編碼。你可以找出 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"的方式都可以避免亂碼的問題發(fā)生

各種請(qǐng)求方式

requests里提供個(gè)各種請(qǐng)求方式

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")

請(qǐng)求

基本GET請(qǐng)求

import requestsresponse = requests.get('http://httpbin.org/get') print(response.text)

帶參數(shù)的GET請(qǐng)求,例子1

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

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

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

上述兩種的結(jié)果是相同的,通過params參數(shù)傳遞一個(gè)字典內(nèi)容,從而直接構(gòu)造url
注意:第二種方式通過字典的方式的時(shí)候,如果字典中的參數(shù)為None則不會(huì)添加到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()))

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

獲取二進(jìn)制數(shù)據(jù)

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

添加headers
和前面我們將urllib模塊的時(shí)候一樣,我們同樣可以定制headers的信息,如當(dāng)我們直接通過requests請(qǐng)求知乎網(wǎng)站的時(shí)候,默認(rèn)是無法訪問的

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

這樣會(huì)得到如下的錯(cuò)誤

因?yàn)樵L問知乎需要頭部信息,這個(gè)時(shí)候我們?cè)诠雀铻g覽器里輸入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請(qǐng)求

通過在發(fā)送post請(qǐng)求時(shí)添加一個(gè)data參數(shù),這個(gè)data參數(shù)可以通過字典構(gòu)造成,這樣
對(duì)于發(fā)送post請(qǐng)求就非常方便

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

同樣的在發(fā)送post請(qǐng)求的時(shí)候也可以和發(fā)送get請(qǐng)求一樣通過headers參數(shù)傳遞一個(gè)字典類型的數(shù)據(jù)

響應(yīng)

我們可以通過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)

結(jié)果如下:

狀態(tài)碼判斷
Requests還附帶了一個(gè)內(nèi)置的狀態(tài)碼查詢對(duì)象
主要有如下內(nèi)容:

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'),

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

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

requests高級(jí)用法

文件上傳

實(shí)現(xiàn)方法和其他參數(shù)類似,也是構(gòu)造一個(gè)字典然后通過files參數(shù)傳遞

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

結(jié)果如下:

獲取cookie

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

會(huì)話維持

cookie的一個(gè)作用就是可以用于模擬登陸,做會(huì)話維持

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

這是正確的寫法,而下面的寫法則是錯(cuò)誤的

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

因?yàn)檫@種方式是兩次requests請(qǐng)求之間是獨(dú)立的,而第一次則是通過創(chuàng)建一個(gè)session對(duì)象,兩次請(qǐng)求都通過這個(gè)對(duì)象訪問

證書驗(yàn)證

現(xiàn)在的很多網(wǎng)站都是https的方式訪問,所以這個(gè)時(shí)候就涉及到證書的問題

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

默認(rèn)的12306網(wǎng)站的證書是不合法的,這樣就會(huì)提示如下錯(cuò)誤

為了避免這種情況的發(fā)生可以通過verify=False
但是這樣是可以訪問到頁面,但是會(huì)提示:
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)

這樣就不會(huì)提示警告信息,當(dāng)然也可以通過cert參數(shù)放入證書路徑

代理設(shè)置

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)

如果代理需要設(shè)置賬戶名和密碼,只需要將字典更改為如下:
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"
}

超時(shí)設(shè)置

通過timeout參數(shù)可以設(shè)置超時(shí)的時(shí)間

認(rèn)證設(shè)置

如果碰到需要認(rèn)證的網(wǎng)站可以通過requests.auth模塊實(shí)現(xiàn)

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

當(dāng)然這里還有一種方式

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

異常處理

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

?

?

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

通過下面的例子進(jìn)行簡單的演示

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")

其實(shí)最后測試可以發(fā)現(xiàn),首先被捕捉的異常是timeout,當(dāng)把網(wǎng)絡(luò)斷掉的haul就會(huì)捕捉到ConnectionError,如果前面異常都沒有捕捉到,最后也可以通過RequestExctption捕捉到

轉(zhuǎn)載于:https://www.cnblogs.com/shuai1991/p/10814937.html

總結(jié)

以上是生活随笔為你收集整理的python之爬虫(四)之 Requests库的基本使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。