python requests庫入門

@[toc]

requests庫安裝

Windows平臺

pip install requests

測試requests的安裝

import requests

r = requests.get("http://www.baidu.com")
print(r.status_code)

print(r.text)
200
<!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>???o|???????? ?

requests庫的7個主要方法

方法 說明
requests.request() 構造一個請求样屠,支撐以下各方法的基礎方法
requests.get() 獲取HTML網(wǎng)頁的主要方法铐炫,對應于HTTP的GET
requests.head() 獲取HTML網(wǎng)頁頭信息的方法相满,對應于HTTP的HEAD
requests.post() 向HTML網(wǎng)頁提交POST請求的方法槐瑞,對應于HTTP的POST
requests.put() 向HTML網(wǎng)頁提交PUT請求的方法跷跪,對應于HTTP的PUT
requests.patch() 向HTML網(wǎng)頁提交局部修改請求,對應于HTTP的PATCH
requests.delete() 向HTML頁面提交刪除請求稚铣,對應于HTTP的DELETE

requests庫的get()方法

requests.get(url,params=None,**kwargs)
  • url:擬獲取頁面的url鏈接
  • params:url中的額外參數(shù)瞧剖,字典或字節(jié)流格式,可選
  • **kwargs:12個控制訪問的參數(shù)
import requests

r = requests.get("http://www.baidu.com")
print(r.status_code)
print(type(r))
print(r.headers)
200
<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': 'Fri, 27 Aug 2021 08:13:17 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:36 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

response對象包含服務器返回的所有信息民假,也包含請求的request信息

response對象的屬性

屬性 說明
r.status_code HTTP請求的返回狀態(tài)浮入,200表示連接成功,404表示失敗
r.text HTTP響應內(nèi)容的字符串形式阳欲,即url對應的頁面內(nèi)容
r.encoding 從HTTP header中猜測的響應內(nèi)容編碼方式
r.apparent_encoding 從內(nèi)容中分析出的響應內(nèi)容編碼方式
r.content HTTP響應內(nèi)容的二進制形式
import requests

r = requests.get("http://www.baidu.com")
print(r.status_code)
print(r.text)
print(r.encoding)
print(r.apparent_encoding)
print(r.content)
=cp-feedback>?
              è§?é|</a>&nbsp;?o?ICPèˉ030173?·&nbsp; <img src=//www
.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

ISO-8859-1
utf-8
b'<!DOCTYPE html>\r\n<!--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=

r.encoding:如果header中不存在charset,則認為編碼為ISO-8859-1,r.text根據(jù)r.encoding顯示網(wǎng)頁內(nèi)容
r.apparent_encoding:根據(jù)網(wǎng)頁內(nèi)容分析出的編碼方式舵盈,可以看做是r.encoding的備選

爬取網(wǎng)頁的通用代碼

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 "產(chǎn)生異常"

if __name__ == "__main__":
    url = "http://www.baidu.com"
    print(getHTMLText(url))
<!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 clas/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 + 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;">更多 
產(chǎn)品</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>

requests庫的方法

requests庫的head()方法
r = requests.head("http://httpbin.org/get")
print(r.headers)

{'Date': 'Fri, 27 Aug 2021 08:35:54 GMT', 'Content-Type': 'application/json', 'Content-Length': '307', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
requests庫的post()方法
payload = {'key1':'value1','key2':'value2'}
r = requests.post("http://httpbin.org/post",data=payload)
print(r.text)
PS E:\coding> python -u "e:\coding\pa.py"
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "key1": "value1",
    "key2": "value2"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "23",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.25.1",
    "X-Amzn-Trace-Id": "Root=1-6128a52f-262035902ff7c33c4f61fe1b"
  },
  "json": null,
  "origin": "36.142.152.189",
  "url": "http://httpbin.org/post"
}

向URL POST一個字典球化,自動編碼為form(表單)
向URL POST一個字符串秽晚,自動編碼為data

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市筒愚,隨后出現(xiàn)的幾起案子赴蝇,更是在濱河造成了極大的恐慌,老刑警劉巖巢掺,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件句伶,死亡現(xiàn)場離奇詭異,居然都是意外死亡陆淀,警方通過查閱死者的電腦和手機考余,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來轧苫,“玉大人楚堤,你說我怎么就攤上這事『茫” “怎么了身冬?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長岔乔。 經(jīng)常有香客問我酥筝,道長,這世上最難降的妖魔是什么雏门? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任嘿歌,我火速辦了婚禮掸掏,結果婚禮上,老公的妹妹穿的比我還像新娘搅幅。我一直安慰自己阅束,他們只是感情好,可當我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布茄唐。 她就那樣靜靜地躺著,像睡著了一般蝇更。 火紅的嫁衣襯著肌膚如雪沪编。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天年扩,我揣著相機與錄音蚁廓,去河邊找鬼。 笑死厨幻,一個胖子當著我的面吹牛相嵌,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播况脆,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼饭宾,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了格了?” 一聲冷哼從身側響起看铆,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎盛末,沒想到半個月后弹惦,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡悄但,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年棠隐,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片檐嚣。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡助泽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出净嘀,到底是詐尸還是另有隱情报咳,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布挖藏,位于F島的核電站暑刃,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏膜眠。R本人自食惡果不足惜岩臣,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一溜嗜、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧架谎,春花似錦炸宵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至会涎,卻和暖如春裹匙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背末秃。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工概页, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人练慕。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓惰匙,卻偏偏與公主長得像,于是被迫代替她去往敵國和親铃将。 傳聞我的和親對象是個殘疾皇子项鬼,可洞房花燭夜當晚...
    茶點故事閱讀 45,573評論 2 359

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