標籤:text ram 返回 enc style password nta ssi 使用者名稱
前言
發送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"
}
五、禪道登入參考代碼
1 # coding:utf-8 2 # coding:utf-8 3 import requests 4 # 禪道host地址 5 host = "http://127.0.0.1" 6 7 def login(s,username,psw): 8 url = host+"/zentao/user-login.html" 9 10 h = {11 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",12 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",13 "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",14 "Accept-Encoding": "gzip, deflate",15 "Referer": host+"/zentao/user-login.html",16 # "Cookie": # 頭部沒登入前不用傳cookie,因為這裡cookie就是保持登入的17 "Connection": "keep-alive",18 "Content-Type": "application/x-www-form-urlencoded",19 }20 21 body1 = {"account": username,22 "password": psw,23 "keepLogin[]": "on",24 "referer": host+"/zentao/my/"25 }26 27 # s = requests.session() 不要寫死session28 29 r1 = s.post(url, data=body1, headers=h)30 # return r1.content # python2的return這個31 return r1.content.decode("utf-8") # python332 33 def is_login_sucess(res):34 if "登入失敗,請檢查您的使用者名稱或密碼是否填寫正確。" in res:35 return False36 elif "parent.location=" in res:37 return True38 else:39 return False40 41 if __name__ == "__main__":42 s = requests.session()43 a = login(s, "admin", "e10adc3949ba59abbe56e057f20f883e")44 result = is_login_sucess(a)45 print("測試結果:%s"%result)46 47
python介面自動化2-發送post請求