Request simulation zhihu login (no verification code mechanism), request verification code
Import request
Try:
Import cookielib # Python 2
Except t:
Import http. cookiejar as cookielib # python3
Import re
Import
Session = request. session ()
Session. cookies = cookielib. LWPCookieJar (filename = "cookies.txt") # store cookies to local files
# Loading cookies
Try:
Session. cookies. load (ignore_discard = True)
Except t:
Print ("cookies cannot be loaded ")
User_Agent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36"
Header = {
"HOST": "www.zhihu.com ",
"Referer": "https://www.zhihu.com ",
"User_Agent": User_Agen"
}
# Obtain xsrf
Def get_xsrf ():
Response = session. post ("https://www.zhihu.com", headers = header) # request a webpage with a header file
Match_obj = re. match ('. * name = "_ xsrf" value = "(.*?) "') # Use single double quotation marks
If match_obj:
Return (match_obj (1 ))
Else:
Return ""
Def get_index ():
Response = session. get ("https://www.zhihu.com", headers = header)
With open ("index_page.heml", wb) as f:
F, write (response. text. encode ("UTF-8 "))
Print ("OK ")
# Simulate zhihu Logon
Def zhihu_login (account, password ):
If re. match ("^ 1 \ d {10}", account): # verify whether the account is a mobile phone number
Print ("Mobile login ")
Post_url = "https://www.zhihu.com/login/phone_num"
Post_data = {
"_ Xsrf": get_xsrf (),
"Phone_num": account,
"Password": password
}
Else:
If "@" in account:
Print ("email login ")
Post_url = "https://www.zhihu.com/login/email"
Post_data = {
"_ Xsrf": get_xsrf (),
"Email": account,
"Password": password
}
Response_text = session. post (post_url, post_data, headers = header)
Session. cookies. save ()
# Verify whether the logon is successful
Def is_login ():
Inbox_url = "https://www.zhihu.com/inbox"
Response = session. get (inbox_url, headers = header, allow_redirects = False)
If response. status_code! = 200:
Return False
Else:
Return True
Zhihu. login ("18782902568", "admin123 ")
Get_index ()