Python form login processing (2)
2. Process cookies
After a sign-on is complete, the code added at the end of the following code, save the login cookies
session.cookies.save()
cookies will be stored in the code file in the same folder. Wherein, cookies have been encrypted data, each cookies would probably define four parameters:
Set-Cookies : name = VALUR;
expires : DATA;
path = PATH;
domain = DOMAIN_NAME;
name is the name of cookies, the general will be encrypted; expires the cookie expiration date and time; path refers to the path of the cookie; domain refers to the domain where the cookie.
Then have preserved cookies can be achieved by loading the login cookies.
import requests
import http.cookiejar as cookielib
#导入所需要的库
session = requests.session()
session,cookies = cookielib.LWPCookieJar(filename='cookies')
try:
session.cookies.load(ignore_discard=True)
except:
pritn("Cookie 未能加载")
#如果没有出现"Cookie 未能加载"说明cookies加载成功。
def isLogin():
url = "http://www.santostang.com/wp-admin/profile.php"
login_code = session.get(url,headers=headers,allow_redirects=False).status_code
if login_code == 200:
return True
else:
return False
#创建一个isLogin函数判断是否登入成功,allow_redirects=False意为禁止重定向
if __name__ == '__main__':
agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
headers = {
'Host' : 'www.santostang.com',
'Origin' : 'http://www.santostang.com',
'Referer' : 'http://www.santostang.com/wp-login.php',
'User-Agent' : agent
}
if isLogin():
print("您已经登入")
The first portion and a second binding portion, when there is no sign of cookies with account password, cookies when loading cookies have signed, combined into the code:
import requests
import http.cookiejar as cookielib
session = requests.session()
session,cookies = cookielib.LWPCookieJar(filename='cookies')
try:
session.cookies.load(ignore_discard=True)
except:
pritn("Cookie 未能加载")
def isLogin():
url = "http://www.santostang.com/wp-admin/profile.php"
login_code = session.get(url,headers=headers,allow_redirects=False).status_code
if login_code == 200:
return True
else:
return False
def Login(secret,account):
post_url = 'http://www.santostang.com/wp-login.php'
postdata = {
'pwd' : secret,
'log' : account,
'remember' : 'forever',
'redirect_to' : 'http://www.santostang.com/wp-admin',
'testcookie' : 1,
}
try:
#不需要验证码直接登入
login_page = session.post(post_url,data = pastdata,headers = headers)
login_code = login_page.text
print(login_page.status_code)
except:
pass
session.cookies.save()
if __name__ == '__main__':
agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
headers = {
'Host' : 'www.santostang.com',
'Origin' : 'http://www.santostang.com',
'Referer' : 'http://www.santostang.com/wp-login.php',
'User-Agent' : agent
}
if isLogin():
print("您已经登入")
else:
login('a12345','test')