處理cookie
雖然python的標準庫中urllib模組已經包含我們平常使用的大多數功能,但是它的api使用起來讓人感覺不太好,而requests使用起來更加方便
利用pip 可以非常方便安裝:
pip install requests
最簡單的傳送get請求的方式就是通過requests.get呼叫:
response=reqquests.get("")
新增headers和查詢引數
如果想要headers,可以傳入headers引數來增加請求頭中headers資訊。如果要將引數傳入url,可以利用params引數。具體例項如下:
import requests
kw=headers=
#params 接收乙個字典或者字串查詢引數,字典型別自動轉化為url編碼
requests=requests.get("s",params=kw,headers=headers)
#檢視響應內容,requests.text返回的是unicode格式資料
print(requests.text)
#檢視響應內容,requests.content返回的是位元組資料
print(requests.content)
#檢視完整url位址
print(requests.url)
#檢視響應頭部字元編碼
print(requests.encoding)
#檢視響應碼
print(requests.statu_code)
requests.text和requests.content比較
requests.text例項
import requests
response=requests.get("")
print(type(response.text))
print(response.text)
requests.content例項
#encoding utf-8
import requests
response=requests.get("")
print(type(response.content))
print(response.content.decode('utf-8'))
import requests
#response=requests.get("")
#print(type(response.content))
#print(response.content.decode('utf-8'))
kw=#params 接收乙個字典或者字串查詢引數,字典型別自動轉化為url編碼
response=requests.get("s",params=kw,headers=headers)
#檢視響應內容,requests.text返回的是unicode格式資料
print(response.url)
傳送post請求非常簡單,直接呼叫』request.post』方法就可以
如果返回的是josn資料。那麼可以呼叫』request.josn()'將josn字串轉換為字典或者列表。
response=reqquests.post(",data-data")
接下來通過訪問拉勾網來演示post請求
#傳送post請求
import requests
import time
data=
url_start = "運維?city=%e6%88%90%e9%83%bd&cl=false&fromsearch=true&labelwords=&suginput="
url_parse = "成都&needaddtionalresult=false"
headers =
s=requests.session()# 建立乙個session物件
s.get(url=url_start,headers=headers,timeout=3)# 用session物件發出get請求,請求首頁獲取cookies
cookie=s.cookies# 為此次獲取的cookies
response=requests.post("",data=data,headers=headers,cookies=cookie,timeout=3)
time.sleep(7)
#print(cookie)
#print(type(response.json()))
print(response.text)
使用**很簡單,只要在請求的方法中傳遞proxies引數就可以
#通過**訪問
import requests
#url=""
proxy=
respones=requests.get("",proxies=proxy)
print(respones.text)
如果想要在多次請求中共享cookie,那麼就應該使用session。**如下:
#處理cookie
#如果想要在多次請求中共享cookie,那麼就應該使用session。**如下:
url=""
data=
headers=
session=requests.session()
session.post(url,data=data,headers=headers)
respones=session.get('')
with open('renren.html','w',encoding='utf-8') as fp:
fp.write(respones.text)
Python爬蟲之Requests庫
所謂爬蟲就是模擬客戶端傳送網路請求,獲取網路響應,並按照一定的規則解析獲取的資料並儲存的程式。要說 python 的爬蟲必然繞不過 requests 庫。對於 requests 庫,官方文件是這麼說的 requests 唯一的乙個非轉基因的 python http 庫,人類可以安全享用。警告 非專業...
python爬蟲之requests庫
在python爬蟲中,要想獲取url的原網頁,就要用到眾所周知的強大好用的requests庫,在2018年python文件年度總結中,requests庫使用率排行第一,接下來就開始簡單的使用requests庫吧.在window環境下,推薦是用pip進行安裝,因為便捷而且不用考慮檔案的解壓路徑 pip...
python網路爬蟲之requests庫
import requests1 requests庫有兩個物件,request物件和response物件,下表是response物件的屬性 屬性說明 r.status code http請求的返回狀態,200表示連線成功,404表示失敗 r.text http響應內容的字串形式,即,url對應的頁面...