这里用python模拟登录知乎,并确定登录的情况:
class ZhiHu(object):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0)'
' Gecko/20100101 Firefox/47.0'}
def __init__(self):
self.session = requests.Session()
def login(self, phone_num, password):
data = {
"_xsrf": self._xsrf(),
"phone_num": phone_num,
"password": password,
"remember_me": True,
"captcha": self._captcha()
}
post_url = 'https://www.zhihu.com/login/phone_num'
r = self.session.post(post_url, data, headers=self.headers)
print(r.json())
def _xsrf(self):
login_url = "https://www.zhihu.com/#signin"
respond = self.session.get(login_url, headers=self.headers)
xsrf = re.search(r'name="_xsrf"\s+value="(.*)"', respond.text)
return xsrf.group(1)
def _captcha(self):
url = 'https://www.zhihu.com/captcha.gif?r={}&type=login'.format((time.time()*1000))
try:
content = self.session.get(url, headers=self.headers).content
with open('captcha.png', 'wb') as f:
f.write(content)
f.close()
except HTTPError:
print('failed to download the captcha image!!!')
exit(1)
print('please enter the captcha: ')
return input().rstrip()
if __name__ == '__main__':
zhihu = ZhiHu()
zhihu.login('xxxxx', 'xxxx')
解析:
1.当然是先建立一个session对象,其会保存网络通信时的信息,包括cookies之类的。
2.用post方法传输表格数据这个就不用多讲啦,至于需要传输哪一些数据的话,用Chrome或360游览器自带的工具进行跟踪查找就行。在登录页面鼠标右键‘检查‘或“审查元素”。
3.值得注意的一点是,提交表单数据的URL与登录页面的URL是不一样的,具体怎么得到,同上使用工具去查找。
4.注意到一个元素xsrf,此为为安全起见的不重复随机数。
5.最后一点就是不要把URL中的https写成http, 前者为密文传输, 后者为明文传输。
6.关于怎样判断登录情况的:代码print(r.json())将得到一个字典,那里可以清楚地看到登陆的情况。
7.代码在python3.6 pychram中通过。
如果上述不能通过或有问题,欢迎评论。
还有。。。。
按照同样的方法尝试登录教务网,为什么不行。。。。。????
导致不敢上传。