session處理
阿新 • • 發佈:2018-12-19
一、session請求
1.登入後會自動儲存cookie,之後直接用儲存cookie的session請求
# coding:utf-8 import requests s = requests.session() # 相當於一個微型的瀏覽器 會儲存cookie login_url = "http://47.xx.xxx.xx:9000/zentao/user-login.html" headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "Upgrade-Insecure-Requests":"1" } body = { "account":"admin", "password":"e10adc3949ba59abbe56e057f20f883e", "referer":"http://47.xx.xxx.xx:9000/zentao/my/" } r = s.post(login_url,headers=headers,data=body,verify=False) req_url = "http://47.xx.xxx.xx:9000/zentao/qa/" r1 = s.get(req_url,headers=headers,verify=False) print(r1.text)
2.繞過驗證碼請求(抓包獲取到cookie,更新cookie請求)
# coding:utf-8 import requests # 不需要登入操作,只需要記錄下登入後的cookie,更新cookie,帶cookie請求 s = requests.session() headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "Upgrade-Insecure-Requests":"1" } coo = requests.cookies.RequestsCookieJar() # 抓包請求獲取到的cookie,"lang=zh-cn; theme=default; windowWidth=1920; windowHeight=969; zentaosid=u8atlrmj586464efuaegfpaf84" coo.set("lang","zh-cn") coo.set("theme","default") coo.set("windowWidth","1920") coo.set("zentaosid","u8atlrmj586464efuaegfpaf84") s.cookies.update(coo) req_url = "http://47.xx.xxx.xx:9000/zentao/qa/" r1 = s.get(req_url,headers=headers,verify=False) print(r1.text)
3.用selenium頁面做登入操作獲取到cookie
使用情況,登入介面分析有難度,有動態資料無法直接獲取,就可以從ui層面去解決
# coding:utf-8 import requests from selenium import webdriver s = requests.session() # 1.用selenium在介面做登入操作後,獲取到cookie driver = webdriver.Chrome() driver.get("http://192.168.1.9:8080/login.do?gotoURL=http%3A%2F%2F192.168.1.9%3A8080%2Fportal%2Fgeoindex.do") driver.maximize_window() driver.implicitly_wait(3) driver.find_element_by_id("userAccount").clear() driver.find_element_by_id("userAccount").send_keys("suner001") driver.find_element_by_id("passwd").clear() driver.find_element_by_id("passwd").send_keys("123456") driver.find_element_by_id("btnlogin").click() coo_1 = driver.get_cookie("JSESSIONID")["value"] coo_2 = driver.get_cookie("SSOID")["value"] cook = { "JSESSIONID":coo_1, "SSOID":coo_2 } # 2. 將獲取到的cookie作為引數傳入 req_url = "http://192.168.1.9:8080/cls/queryList_ClsInfo.do?classType=1&limit=10&offset=0" headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "Origin":"http://192.168.1.9:8080", "Referer":"http://192.168.1.9:8080/exam/page_myPaperList.do", } body = { "search":"" } r = s.post(req_url,headers=headers,cookies=cook,json=body,verify=False) print(r.text)