Python 爬蟲二 requests模塊


requests模塊

 

Requests模塊

get方法請求

整體演示一下:

import requests

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

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

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

import requests
response = requests.get(
    url='https://www.autohome.com.cn/news/'
)
response.encoding = response.apparent_encoding  # 使用默認的編碼原則
print(response.text)

一個簡單的get請求的爬蟲結果:

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

# 實例方法一
import requests
response = requests.get("url?name=dandy&age=18")
print(response.text)


# 實例方法二
import requests
url = ''
data = {
    "name":"dandy",
    "age":18
}
response = requests.get(url,params=data)
print(response.url)
print(response.text)

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

 

獲取二進制數據

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

 

添加headers
和前面我們將urllib模塊的時候一樣,我們同樣可以定制headers的信息,如當我們直接通過requests請求知乎網站的時候,默認是無法訪問的。谷歌瀏覽器里輸入chrome://version,就可以看到用戶代理,將用戶代理添加到頭部信息:

也可以隨便輸入一個網址:

都可以獲取到。 

copy出來仿造的請求頭信息

import requests
url = ''
headers = {

    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
response =requests.get(url,headers=headers)

print(response.text)

 

post請求

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

import requests
url = ''
data = {
    "name":"dandy",
    "age":18
}
response = requests.post(url,data=data)
print(response.text)

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

 

模擬登陸&自動點贊

首先打開抽屜,點擊登陸,打開開發者模式,隨意的輸入賬號密碼,然后點擊登陸,可以的到如下的圖:

備注:之前抽屜是不會去抓去請求頭的終端設備信息的,現在有驗證了,0.0

首先需要大佬們去注冊一下賬號密碼,然后我們來模擬瀏覽器登陸,這里需要注意的一點是,登陸的時候可以注意一下,如果瀏覽器刷新了,那肯定是form驗證,如果沒有那就一定是ajax驗證。所以這里不用說,測試一下就發現是ajax驗證:

import requests
headers = {
    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}  # header里偽造終端信息
post_dict = {
    'phone': '8615988888888',
    'password': '*******',
    'oneMonth': 1
}
response = requests.post(
    url='https://dig.chouti.com/login',
    data=post_dict,
    headers=headers
)
print(response.content)
cookie_dict = response.cookies.get_dict()
print(cookie_dict)

這里,既然是ajax登陸,返回的可以猜到一定是json數據:

b'{"result":{"code":"9999", "message":"", "data":{"complateReg":"0","destJid":"cdu_51970753537"}}}'
{'gpsd': '4fa04e9978e550f8d6ea1fb5418184ee', 'puid': 'c3c133fab0b2ba4bcb5e0f9b494501cd', 'JSESSIONID': 'aaahPA3kgUc2yhWM_9xsw'}

到現在為止,已經順利的實現了登陸功能,然后實現了,大家應該都知道為什么要抓取一下cookies打印出來吧?

cookies的真正的意義就是在於當第一次登陸完,之后就可以直接帶着服務器返回的cookies去向服務器發送請求。之后就可以肆意妄為了!!!

現在我們來實現一下自動點贊的功能,首先找一篇文章,點個贊:

由上,可以發現點贊的網址,post的數據等,此時取消點贊,寫代碼:

import requests
headers = {
    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
post_dict = {
    'phone': '8615962180289',
    'password': 'zhangy321281',
    'oneMonth': 1
}
response = requests.post(
    url='https://dig.chouti.com/login',
    data=post_dict,
    headers=headers
)
print(response.content)
cookie_dict = response.cookies.get_dict()
print(cookie_dict)

response_vote = requests.post(
    url='https://dig.chouti.com/link/vote?linksId=20819056',
    cookies=cookie_dict
)
print(response_vote)

信心滿滿寫好了:

b'{"result":{"code":"9999", "message":"", "data":{"complateReg":"0","destJid":"cdu_51970753537"}}}'
{'gpsd': '74338b2cda9e9a355a52854b95474e3a', 'puid': '07fd1754895aefa93b4b46fb52990f7f', 'JSESSIONID': 'aaavRXk12M4Kidy5_9xsw'}
<Response [403]>

什么??怎么會這樣??拿着瀏覽器返回的cookie怎么不可以呢?那該怎么辦?

管不了那么多,先用笨方法來測試cookies里面哪一個控制這登陸狀態認證:

取消點贊,重新測試代碼點贊:

import requests
headers = {
    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
response = requests.post(
    url='https://dig.chouti.com/link/vote?linksId=20819056',
    cookies={
        'gpsd': '5db40ff97b8dd603f70288157d2bdd8f'  # 因為沒辦法,所以只能用瀏覽器的cookies做驗證,一次次取一個值
    },
    headers=headers
)
print(response.text)

測試結果:

{"result":{"code":"9999", "message":"推薦成功", "data":{"jid":"cdu_51970753537","likedTime":"1531564084343000","lvCount":"10","nick":"衰Zzz","uvCount":"1","voteTime":"小於1分鍾前"}}}

天吶!!!成功了!!!

 

所以我們可以先跟蹤確定了,肯定是gpsd有問題。

這時候退出登陸重新刷新網頁:

記錄一下cookies:

cookie: gpsd=5db40ff97b8dd603f70288157d2bdd8f; gpid=d4a8c7f4454841bd8bd640f5f5565420; JSESSIONID=aaaKh89UOAJIy_PfW8xsw

不免有些疑問,為什么第一次get就有cookies,

此時我們再用代碼測試一下gpsd的值:

import requests
headers = {
    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
response_get = requests.get(
    url='https://dig.chouti.com/',
    headers=headers
)
print(response_get.cookies.get_dict())
post_dict = {
    'phone': '8615988888888',
    'password': '********',
    'oneMonth': 1
}
response_post = requests.post(
    url='https://dig.chouti.com/login',
    data=post_dict,
    headers=headers
)
print(response_post.content)
cookie_dict = response_post.cookies.get_dict()
print(cookie_dict)

查看cookies對比:

{'gpsd': '38644be424cebb27e1cc631dd84ae9d2', 'JSESSIONID': 'aaaKwMAE52emjedIW-xsw'}
b'{"result":{"code":"9999", "message":"", "data":{"complateReg":"0","destJid":"cdu_51970753537"}}}'
{'gpsd': '7b32421f6a73365b2dbb6b9739afaaff', 'puid': '497b5a7249b8538e70ac87ead562c91f', 'JSESSIONID': 'aaa5sbGP7XecWf15W8xsw'}

發現兩次的gpsd不一致,從web開發者角度登陸之后的cookies一定是不會再去進行改變,所以前后一共就有這么兩種可能性的cookies,上面的點贊失敗了,那就代表返回的cookies一定是沒有用的:

那是不是可以猜想認證的gpsd會不會是第一次的gpsd值,但是一想又不太可能,因為第一次的還沒有認證,怎么能保證呢?那會不會是第一次的gpsd再登陸的時候傳過去做了認證,然后瀏覽器記錄了它,但是為了防止爬蟲做了一份假的gpsd給你 ,想到這里不免想測試一下:

import requests
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
response_get = requests.get(
    url='https://dig.chouti.com/',
    headers=headers
)
r1 = response_get.cookies.get_dict()  # 第一次get請求獲取服務器給的cookies
post_dict = {
    'phone': '8615988888888',
    'password': '********',
    'oneMonth': 1,
}
response_post = requests.post(
    url='https://dig.chouti.com/login',
    data=post_dict,
    headers=headers,
    cookies=r1  # 第二次再把第一次得到的cookies傳回去進行認證授權
)
print(response_post.content)
r2 = response_post.cookies.get_dict()  # 這個是個騙子!!!

response_vote = requests.post(
    url='https://dig.chouti.com/link/vote?linksId=20819056',
    cookies={
        'gpsd': r1['gpsd']
    },
    headers=headers
)
print(response_vote.text)

測試結果:

b'{"result":{"code":"9999", "message":"", "data":{"complateReg":"0","destJid":"cdu_51970753537"}}}'
{"result":{"code":"9999", "message":"推薦成功", "data":{"jid":"cdu_51970753537","likedTime":"1531565602774000","lvCount":"16","nick":"衰Zzz","uvCount":"1","voteTime":"小於1分鍾前"}}} 

完成!!

爬蟲登陸GitHub實戰:https://www.cnblogs.com/wuzdandz/p/9338543.html

請求

前面已經講過基本的GET請求,下面稍微詳談一下帶參數的請求:

import requests
# 方法一
response = requests.get('http://****.com/?name=dandy&age=18')
print(response.text)

# 方法二
import requests
data = {
    "name":"dandy",
    "age":18
}
response = requests.get("http://*****.com",params=data)
print(response.url)  # 提交url
print(response.text)
本質上方法二會被轉換成方法一
    請求頭:
        content-type:application/url-form-encod......
    請求體:
        user=dandy&age=18
    局限性在於傳遞的value只能是字符串,數字,列表,不能是字典,

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

 

json

import requests
import json
url = ''
response = requests.get(url)
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json()))

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

data = {'user': 'dandy', 'age': 18}    ==>    json數據 "{'user': 'dandy', 'age': 18}"
    請求頭:
        content-type:application/json....
    請求體:
        user=dandy&age=18
    可以傳遞字典嵌套的字典

獲取二進制數據

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

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

之前的實例抽屜自動登陸,就定制了請求頭headers

Referer:
    requests.request(
        method="POST",
        url = url1,
        params={'k1': v1, 'k2': 'v2'},
        json = {'user': 'dandy', 'age': 18}
        headers={
            "Referer": url/login,  # 判斷上一次請求的網站是不是也是本網站,不是的話默認為非正常訪問
            "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
        }
    )

 

cookie

import requests

response = requests.get("http://www.baidu.com")
print(response.cookies)

for k, v in response.cookies.items():
    print(k + "=" + v)

Cookie放在請求頭里面發送的

 

POST請求

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

import requests

data = {
    "name":"dandy",
    "age":18
}
response = requests.post("http://*****.com",data=data)
print(response.text)

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

*************************************************************************************
在Django內部,如果是以post傳遞過去數據data = {'user': 'dandy', 'age': 18};
請求頭:
content-type:application/url-form-encod......
請求體:
user=dandy&age=18
根據請求頭的不同決定是否請求體里面的data轉換並放到request.POST里面
*************************************************************************************

 

響應

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

import requests

response = 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 requests

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

 

requests高級用法

文件上傳

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

requests.post(
    url='xxx',
    files={
        'f1': open('a.csv', 'rb'),  # 上傳文件對象,默認名稱為文件名稱
        'f2': (filename, open('b.csv', 'rb'))  # 自定義文件名
        }
)

 

證書認證

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

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

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

為了避免這種情況的發生可以通過verify=False,這樣是可以訪問到頁面的:

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

結果如下:

certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
200

解決方法:

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

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

關於證書有兩種:

verify:證書    https:    ==>    ssl加密
    requests.get(
        url='https://...',
        cert='abc.pem',  # 自己制作的證書    pem證書格式
    )

    requests.get(  # 廠商制作好的,在系統創建時就已經植入,直接購買權限
        url='https://...',
        cert=('abc.crt', 'xxx.key'),

                    
    )
    verify:False  忽略證書,直接交互

代理設置

import requests

proxies= {
    "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"
}

請求不是發送到目的URL的,而是先發送給代理,代理再去發送請求

 

超時設置

通過timeout參數可以設置超時的時間,等服務器多長時間放棄

(a,b)    ==>    a 發送最長時間;b 等待最長時間

 

 

認證設置

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

import requests

from requests.auth import HTTPBasicAuth

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

另一種方式:

import requests

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

基本登陸框 md5加密請求頭發送過去, 用戶名&密碼

 

 

重定向設置

allow-redirects:是否允許重定向到新的地址拿數據

 

分流迭代設置

流,如果為false,會一次性下載,如果為true,會一點一點的下載,迭代拿 

 

session設置(持久化)

還記得前面大費周章的去把cookies值裝進headers,重新認證么?現在用session來改寫一下!!!

import requests
session = requests.Session()

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
# 1、首先登陸任何頁面,獲取cookie
r1 = session.get(
    url='https://dig.chouti.com/',
    headers=headers
)
# 2、用戶登陸,攜帶上一次的cookie,后台對cookie中的gpsd進行授權
post_dict = {
    'phone': '8615988888888',
    'password': 'zhang1111111',
    'oneMonth': 1,
}
r2 = session.post(
    url='https://dig.chouti.com/login',
    data=post_dict,
    headers=headers
)
# 點贊
r3 = session.post(
    url='https://dig.chouti.com/link/vote?linksId=20819051',
    headers=headers
)
print(r3.text)

結果輸出:

{"result":{"code":"9999", "message":"推薦成功", "data":{"jid":"cdu_51970753537","likedTime":"1531744254481000","lvCount":"5","nick":"衰Zzz","uvCount":"2","voteTime":"小於1分鍾前"}}}

直接從開始就持久化。。問題迎刃而解。

 

異常處理 

http://www.python-requests.org/en/master/api/#exceptions

Exceptions

exception  requests. RequestException (*args**kwargs)[source]

There was an ambiguous exception that occurred while handling your request.

exception  requests. ConnectionError (*args**kwargs)[source]

A Connection error occurred.

exception  requests. HTTPError (*args**kwargs)[source]

An HTTP error occurred.

exception  requests. URLRequired (*args**kwargs)[source]

A valid URL is required to make a request.

exception  requests. TooManyRedirects (*args**kwargs)[source]

Too many redirects.

exception  requests. ConnectTimeout (*args**kwargs)[source]

The request timed out while trying to connect to the remote server.

Requests that produced this error are safe to retry.

exception  requests. ReadTimeout (*args**kwargs)[source]

The server did not send any data in the allotted amount of time.

exception  requests. Timeout (*args**kwargs)[source]

The request timed out.

Catching this error will catch both ConnectTimeout and ReadTimeout errors.

 

源代碼、詳細異常關系:http://cn.python-requests.org/zh_CN/latest/_modules/requests/exceptions.html#RequestException 

從源碼我們可以看出RequestException繼承IOError,
HTTPError,ConnectionError,Timeout繼承RequestionException
ProxyError,SSLError繼承ConnectionError
ReadTimeout繼承Timeout異常

簡單sample:

import requests

from requests.exceptions import ReadTimeout,ConnectionError,RequestException


try:
    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,當把網絡斷掉就會捕捉到ConnectionError,如果前面異常都沒有捕捉到,最后也可以通過RequestExctption捕捉到

 

參照:zhaofan老師的blog http://www.cnblogs.com/zhaof/p/6915127.html

參照源碼:

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) <timeouts>` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      <Response [200]>
    """

    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM