Python requests 使用手冊

Python 內(nèi)置了 requests 模塊振惰,該模塊主要用來發(fā) 送 HTTP 請求钞楼,requests 模塊比 urllib 模塊更簡潔示辈。

語法:

requests.methodname(params)

方法

Method Description
delete(url, args) Sends a DELETE request to the specified url
get(url, params, args) Sends a GET request to the specified url
head(url, args) Sends a HEAD request to the specified url
patch(url, data, args) Sends a PATCH request to the specified url
post(url, data, json, args) Sends a POST request to the specified url
put(url, data, args) Sends a PUT request to the specified url
request(method, url, args) Sends a request of the specified method to the specified url

例如

 # 導(dǎo)入 requests 包
import requests

url = "http://httpbin.org"
 # 發(fā)送請求
x = requests.get(url)
 
 # 返回 http 的狀態(tài)碼
print(x.status_code)

# 響應(yīng)狀態(tài)的描述
print(x.reason)

# 返回編碼
print(x.apparent_encoding)

輸出結(jié)果如下:

200
OK
Windows-1252

對于帶參數(shù)的URL吓歇,傳入一個dict作為params參數(shù):

結(jié)果是改變 url -> url + ?key=value

>>> url = "http://httpbin.org/get" 
>>> params = { "key1": "value1", "key2": "value2"}
>>> y = requests.get(url, params = params)
>>> print(y.url)
http://httpbin.org/get?key1=value1&key2=value2

添加 headers

>>> headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
>>> url = 'https://www.douban.com/'
>>> r = requests.get(url, headers=headers)
>>> print(r.status_code)
200

具體的屬性和方法可以參考這里:Python requests.Response Object (w3schools.com)

如果是 post:

>>> url = "http://httpbin.org/post"
>>> payload = {"name": "roy", "age": "80"}
>>> r = requests.post(url, data = payload)
>>> print(r.reason)
OK

>>> import requests
>>> r = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json'
>>> r.headers
{'Date': 'Fri, 28 Oct 2022 01:36:58 GMT', 'Content-Type': 'application/json', 'Content-Length': '47', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
>>> r.encoding
>>> r.text
'{\n  "authenticated": true, \n  "user": "user"\n}\n'
>>> r.json()
{'authenticated': True, 'user': 'user'}
>>>

Python Requests get() Method

The get() method sends a GET request to the specified url.


Syntax

requests.get(url, params={"key": "value"}, args)

args means zero or more of the named arguments in the parameter table below. Example:

requests.get(url, timeout=2.50)

Parameter Values

Parameter Description
url Required. The url of the request
params Optional. A dictionary, list of tuples or bytes to send as a query string. Default None
allow_redirects Optional. A Boolean to enable/disable redirection. Default True (allowing redirects)
auth Optional. A tuple to enable a certain HTTP authentication. Default None
cert Optional. A String or Tuple specifying a cert file or key. Default None
cookies Optional. A dictionary of cookies to send to the specified url. Default None
headers Optional. A dictionary of HTTP headers to send to the specified url. Default None
proxies Optional. A dictionary of the protocol to the proxy url. Default None
stream Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True). Default False
timeout Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a response. Default None which means the request will continue until the connection is closed
verify Optional. A Boolean or a String indication to verify the servers TLS certificate or not. Default True

Return Value

The get() method returns a requests.Response object.

Python Requests post() Method

Example

Make a POST request to a web page, and return the response text:

import requests

url = 'https://www.w3schools.com/python/demopage.php'
myobj = {'somekey': 'somevalue'}

x = requests.post(url, json = myobj)

print(x.text)

Definition and Usage

The post() method sends a POST request to the specified url.

The post() method is used when you want to send some data to the server.


Syntax

requests.post(url, data={"key": "value"}, json={"key": "value"}, args)

args means zero or more of the named arguments in the parameter table below. Example:

requests.post(url, data = myobj, timeout=2.50)

Parameter Values

Parameter Description
url Required. The url of the request
data Optional. A dictionary, list of tuples, bytes or a file object to send to the specified url
json Optional. A JSON object to send to the specified url
files Optional. A dictionary of files to send to the specified url
allow_redirects Optional. A Boolean to enable/disable redirection. Default True (allowing redirects)
auth Optional. A tuple to enable a certain HTTP authentication. Default None
cert Optional. A String or Tuple specifying a cert file or key. Default None
cookies Optional. A dictionary of cookies to send to the specified url. Default None
headers Optional. A dictionary of HTTP headers to send to the specified url. Default None
proxies Optional. A dictionary of the protocol to the proxy url. Default None
stream Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True). Default False
timeout Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a response. Default None which means the request will continue until the connection is closed
verify Optional. A Boolean or a String indication to verify the servers TLS certificate or not. Default True

Return Value

A requests.Response object.

參考:

官網(wǎng):Requests: HTTP for Humans? — Requests 2.28.1 documentation

https://www.w3schools.com/python/module_requests.asp

Python requests 模塊 | 菜鳥教程 (runoob.com)

requests - 廖雪峰的官方網(wǎng)站 (liaoxuefeng.com)

python的requests模塊詳解 - 馬昌偉 - 博客園 (cnblogs.com)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末魄幕,一起剝皮案震驚了整個濱河市躏救,隨后出現(xiàn)的幾起案子苛秕,更是在濱河造成了極大的恐慌肌访,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件艇劫,死亡現(xiàn)場離奇詭異吼驶,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門蟹演,熙熙樓的掌柜王于貴愁眉苦臉地迎上來风钻,“玉大人,你說我怎么就攤上這事酒请÷饧迹” “怎么了?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵羞反,是天一觀的道長布朦。 經(jīng)常有香客問我,道長昼窗,這世上最難降的妖魔是什么是趴? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮澄惊,結(jié)果婚禮上唆途,老公的妹妹穿的比我還像新娘。我一直安慰自己掸驱,他們只是感情好肛搬,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著亭敢,像睡著了一般滚婉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上帅刀,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機與錄音远剩,去河邊找鬼扣溺。 笑死,一個胖子當著我的面吹牛瓜晤,可吹牛的內(nèi)容都是我干的锥余。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼痢掠,長吁一口氣:“原來是場噩夢啊……” “哼驱犹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起足画,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤雄驹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后淹辞,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體医舆,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蔬将。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片爷速。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖霞怀,靈堂內(nèi)的尸體忽然破棺而出惫东,到底是詐尸還是另有隱情,我是刑警寧澤毙石,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布凿蒜,位于F島的核電站,受9級特大地震影響胁黑,放射性物質(zhì)發(fā)生泄漏废封。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一丧蘸、第九天 我趴在偏房一處隱蔽的房頂上張望漂洋。 院中可真熱鬧,春花似錦力喷、人聲如沸刽漂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽贝咙。三九已至,卻和暖如春拂募,著一層夾襖步出監(jiān)牢的瞬間庭猩,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工陈症, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蔼水,地道東北人。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓录肯,卻偏偏與公主長得像趴腋,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子论咏,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容