前言
發送post的請求參考例子很簡單,實際遇到的情況卻是很復雜的,首先第一個post請求肯定是登錄了,但登錄是最難處理的。登錄問題解決了,后面都簡單了。
一、查看官方文檔
1.學習一個新的模塊,其實不用去百度什么的,直接用help函數就能查看相關注釋和案例內容。
>>import requests
>>help(requests)
2.查看python發送get和post請求的案例
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
二、發送post請求
1.用上面給的案例,做個簡單修改,發個post請求
2.payload參數是字典類型,傳到如下圖的form里
三、json
1.post的body是json類型,也可以用json參數傳入。
2.先導入json模塊,用dumps方法轉化成json格式。
3.返回結果,傳到data里
四、headers
1.以禪道登錄為例,模擬登陸,這里需添加請求頭headers,可以用fiddler抓包
2.講請求頭寫成字典格式
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json; charset=utf-8",
"X-Requested-With": "XMLHttpRequest",
"Cookie": "xxx.............", # 此處cookie省略了
"Connection": "keep-alive"
}
五、禪道登錄參考代碼
# coding:utf-8
# coding:utf-8
import requests
# 禪道host地址
host = "http://127.0.0.1"
def login(s,username,psw):
url = host+"/zentao/user-login.html"
h = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate",
"Referer": host+"/zentao/user-login.html",
# "Cookie": # 頭部沒登錄前不用傳cookie,因為這里cookie就是保持登錄的
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
}
body1 = {"account": username,
"password": psw,
"keepLogin[]": "on",
"referer": host+"/zentao/my/"
}
# s = requests.session() 不要寫死session
r1 = s.post(url, data=body1, headers=h)
# return r1.content # python2的return這個
return r1.content.decode("utf-8") # python3
def is_login_sucess(res):
if "登錄失敗,請檢查您的用戶名或密碼是否填寫正確。" in res:
return False
elif "parent.location=" in res:
return True
else:
return False
if __name__ == "__main__":
s = requests.session()
a = login(s, "admin", "e10adc3949ba59abbe56e057f20f883e")
result = is_login_sucess(a)
print("測試結果:%s"%result)
---------------------------------python接口自動化完整版-------------------------
全書購買地址 https://yuedu.baidu.com/ebook/585ab168302b3169a45177232f60ddccda38e695
作者:上海-悠悠 QQ交流群:588402570
也可以關注下我的個人公眾號: