requests模組學習筆記

2021-10-25 09:42:13 字數 1813 閱讀 2531

1、request模組的徐誒西

安裝:pip install requests

###傳送get、post請求、獲取響應

–response = requests.get(url) #傳送get請求,請求url位址對應的響應

–response = requests。post(url, data= ##傳送post請求

###response的方法

-response.text

-該方式往往會出現亂碼,出現亂碼使用response.conding=「utf-8」

–response.content.decode()

–把響應的二進位制位元組流轉化為str型別

###獲取網頁原始碼的正確開啟方式(通過下面三種方式一定能夠獲取到網頁的正確解碼之後的字串)

-1、response.content.decode()

-2、response.content.decode(「gbk」)

-3、response.text

###傳送帶header的請求(為了模擬瀏覽器,獲取和瀏覽器一模一樣的內容)

header =

response = requests.post(url,data=data,headers=header)

response = requests.get(url,headers=header) --response.request.url #傳送請求的url位址

–response.url #response響應的url位址

–response.request.header #請求頭

–response.headers #響應請求

###使用超時引數

requests.get(url,headers=headers,timeout=3) #3秒內必須返回響應,否則會報錯

###retrying模組的學習

-pip install retrying

from retrying import retry

@retry(stop_max_attempt_number=3)

def fun1():

print(「this is func1」)

raise valueerror(「this is test erro」)

###處理cookie相關的請求

–人人網

-直接攜帶cookie請求url位址

-1、cookie放在header中

headers=

-2、cookie字典傳給cookie引數

#將字串形式的cookie轉化為字典型別的cookie

cookie_dict=

-requests.get(url,cookies=cookie_dict)

-先傳送post請求,獲取cookie,帶上cookie請求登入後的頁面

-1、session = request.session() #session具有的方法和requests一樣

-2、session.post(url,data,headers)#伺服器設定在本地的cookie會儲存在session

session.post(post_url,headers=headers,data=post_data) //post_data =; . //post_url= 「http:// www.renren.com/plogin.do」 #登入時form表單的位址

-3、seesion.get()#會帶上之前儲存在session中的cookie,能夠請求成功

url = " //登入後頁面的url

response = session.get(url,headers=headers)

requests 學習筆記

除了get 方式外 還有post 等等 注意字典裡值為none的鍵都不會被新增到 url 的查詢字串裡 import requests getpara r requests.get params getpara print r.url r.url key1 value1 keu2 value2 r....

python爬蟲學習 requests模組

python中原生的一款基於網路請求的模組,功能非常強大,簡單便捷,效率極高。作用 模擬瀏覽器發請求。如何使用 requests模組的編碼流程 指定url 發起請求 獲取響應資料 持久化儲存 環境安裝 pip install requests 練習 1.爬取搜狗首頁的頁面資料 需求 爬取搜狗首頁資料...

python 學習筆記 requests

開始學習python 語言,從網上爬取資料並儲存,發現直接下邊 不行 importrequests r requests.get print r.status code print r.headers print r.encoding r.encoding utf 8 print print r.t...