import requestpython
try:cookie
import cookielib #python2版本session
except:post
import http.cookiejar as cookielib #python3版本url
import recode
session=request.session()utf-8
session.cookies=cookielib.LWPCookieJar(filename="cookies.txt") #將cookies存儲到本地文件get
#加載cookies文件it
try:io
session.cookies.load(ignore_discard=True)
except:
print("cookies未能加載")
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"
}
#獲取xsrf
def get_xsrf():
response=session.post("https://www.zhihu.com",headers=header) #請求網頁需帶上頭文件
match_obj=re.match(' .*name="_xsrf" value="(.*?)" ') #注意使用單雙引號
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")
#模擬知乎登陸
def zhihu_login(account,password):
if re.match("^1\d{10}",account): #驗證帳號是否爲手機號
print ("手機登陸")
post_url="https://www.zhihu.com/login/phone_num"
post_data={
"_xsrf" : get_xsrf(),
"phone_num" : account,
"password" : password
}
else:
if "@" in account:
print (「郵箱登陸」)
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()
#驗證是否登陸成功
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()