python3使用requests模塊完成get/post/代理/自定義header/自定義Cookie

 1、背景說明

http請求的難易對一門語言來講是很重要的並且是愈來愈重要,但對於python一是urllib一些寫法不太符合人的思惟習慣文檔也至關難看,二是在python2.x和python3.x中寫法還有差異。html

實在是太難用,開始差點因爲這個緣由想放棄python,直到看urllib.request文檔時看到下邊這句話,認識了requests。總的而言requests配得上「HTTP for Humans」的口號。python

1.1 適用版本

適用於python2.六、python2.七、python3.4及以上版本,參見官方說明。我這裏使用的是當前最新的python3.7。json

 

1.2 安裝requests模塊

pip install requests
# ubuntu類系統也能夠直接用apt安裝
# sudo apt-get install python-requests

 

2、使用requests模塊完成各類操做

下邊對於https的連接請求時會帶上」verify=False「參數,由於默認Python會進行證書校驗若是不是信任的證書會報錯,帶上」verify=False「指示不進行證書校驗。ubuntu

2.1 引用requests模塊

import requests

 

2.2 get請求

import requests

url='https://www.baidu.com'
r = requests.get(url,verify=False)
print(r.status_code)

 

2.3 post請求

import requests

url='https://www.baidu.com'
data='username=ls&password=toor'
r = requests.post(url,data=data,verify=False)
print(r.status_code)

當前不少api是以json形式提交的,因此在使用post的時候咱們可能想提交json數據。python3.x

提交json有兩步:一是data要編碼成json形式(python中的字典形式上和json同樣但本質上不同因此要編碼),二是設置「Content-type」頭的值爲application/json(設置頭部參見下面2.5,這裏先用)api

import json
import requests

# 必定要設置Content-Type值爲application/json
headers={}
headers['Content-Type']='application/json'

url='https://www.baidu.com'
data={"username":"ls","password":"toor"}
# 必定要用json.dumps把data格式化成json
# r = requests.post(url,headers=headers,data=json.dumps(data),verify=False)
# 或者直接使用json參數代替data,此時requests會自動進行格式化和設置Content-Type頭的工做
r = requests.post(url,json=data,verify=False)
print(r.status_code)

爲了方便對比驗證,另外再附curl post提交的方法:cookie

 curl -H "Content-Type:application/json" -X POST --data '{"username": "ls","password":"toor"}' https://www.baidu.com/

 

2.4 使用代理

import requests

url='http://docs.python-requests.org/en/master/'
proxies={
    'http':'127.0.0.1:8080',
    'https':'127.0.0.1:8080'
}
r = requests.get(url,proxies=proxies)
print(r.status_code)

 

 

2.5 自定義header

import requests

url='http://docs.python-requests.org/en/master/'
headers={
    'User-Agent':'self-defind-user-agent',
    'Cookie':'name=self-define-cookies-in header'
}
r = requests.get(url,headers=headers)
print(r.status_code)

 

 

2.6 自定義Cookie

實驗發現若是自定義header中定義了cookies那麼此處設置的cookies不生效session

import requests

url='http://docs.python-requests.org/en/master/'
cookies={'name1':'cookie1','name2':'cookies2'}
#cookies=dict(name1='cookie1',name2='cookies2')
r = requests.get(url,cookies=cookies)
print(r.status_code)

 

2.7 會話保執

常常不少請求只有在登陸後才能進行,實現登陸效果通常的作法是執行登陸請求,而後從返回結果中提取sessionid放入自定義cookie中。app

這種方法在requests中也行得通,但requests提供了更爲簡單的方法,直接使用request.Session類來請求便可,其保持登陸的原理是保留以前請求中服務端經過set-cookie等設置的參數。python2.7

s = Session()
url='http://docs.python-requests.org/en/master/'
# 全部方法和直接使用requests時同樣用便可
s.get(url)

 

參考:

http://docs.python-requests.org/en/master/(官方文檔)

http://www.javashuo.com/article/p-qhesnjmy-bt.html

https://stackoverflow.com/questions/9733638/post-json-using-python-requests

相關文章
相關標籤/搜索