# Coding:utf-8
Import requests
Import re
From BS4 import BeautifulSoup
# s = requests.session () # Global S
def Get_token (s):
‘‘‘
Fuction: Get token
Args:s parameter-"s = requests.session ()
: Return anti_token->{' x-anit-forge-token ': ' xx ', ' x-anit-forge-code ': ' 38515842 '}
‘‘‘
# local s not defined, incoming s from outside
url = ' https://passport.lagou.com/login/login.html '
H1 = {
"User-agent": "mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) gecko/20100101 firefox/44.0 "
}
R1 = s.get (URL, headers=h1, verify=false)
# Print (R1.text)
Soup = BeautifulSoup (r1.content, "Html.parser", from_encoding= ' Utf-8 ')
Tokencode = {}
Try
t = soup.find_all (' script ') [1].get_text ()
Print (t)
tokencode[' X_anti_forge_token ' = Re.findall (r "Token = ' (. +?) '", T) [0]
tokencode[' X_anti_forge_code ' = Re.findall (r "Code = ' (. +?) '", T) [0]
Return Tokencode
Except
Print ("Get token and code failed")
tokencode[' x_anti_forge_token '] = ""
tokencode[' x_anti_forge_code '] = ""
Return Tokencode
def LOGIN_LGW (S, anti_token, User, PSW):
Url2 = ' Https://passport.lagou.com/login/login.json '
H2 = {
"User-agent": "mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) gecko/20100101 firefox/44.0 ",
"Content-type": "application/x-www-form-urlencoded; Charset=utf-8 ",
"X-requested-with": "XMLHttpRequest",
"X-anit-forge-token": anti_token[' X_anti_forge_token '),
"X-anit-forge-code": anti_token[' X_anti_forge_code '),
"Referer": "Https://passport.lagou.com/login/login.html"
}
Body ={
"Isvalidate": "true",
"username": User,
"Password": PSW,
"Request_form_verifycode": "",
"Submit": ""
}
Print (s.headers) # S of the head
# Update the head of S
S.headers.update (H2)
Print (s.headers)
r2 = S.post (Url2, Data=body, Verify=false)
Print (R2.text)
Return R2.json ()
if __name__ = = "__main__":
# Self-Test content
s = requests.session ()
token = Get_token (s)
Print (token)
user = "1232"
PSW = "322222"
LOGIN_LGW (s, token, user, PSW)
Python interface Automation Test 20: Function Write interface test