<file_sep># -*- coding: utf-8 -*-

import urllib
import urllib2
import re
import cookielib
import logging
import os
import json

logging.basicConfig(level=logging.DEBUG)
cookies = cookielib.LWPCookieJar('cookies.txt')
try:
    cookies.load(ignore_discard=True)
except:
    pass

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)


def login():
    if islogin():
        logging.info('Already logged in')
        return True
    url = 'http://www.zhihu.com/login/email'
    user = '<EMAIL>'
    passwd = '<PASSWORD>'
    form = {'email': user, 'password': <PASSWORD>, 'remember_me': True}
    form['_xsrf'] = get_xsrf()
    form['captcha'] = get_captcha()
    post_data = urllib.urlencode(form)
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
        'Host': "www.zhihu.com",
        'Origin': "http://www.zhihu.com",
        'Pragma': "no-cache",
        'Referer': "http://www.zhihu.com/",
        'X-Requested-With': "XMLHttpRequest"
    }
    request = urllib2.Request(url, post_data, headers)
    r = urllib2.urlopen(request)
    if int(r.getcode()) != 200:
        raise RuntimeError("Upload failed!")

    if r.headers['content-type'].lower() == "application/json":
        try:
            result = json.loads(r.read())
        except Exception as e:
            logging.error("JSON parse failed!")
            logging.debug(e)
            return None
        if result["r"] == 0:
            logging.info("Loggin success!")
            cookies.save()
            return True
        elif result["r"] == 1:
            logging.error("Loggin failed!")
            print {"error": {"code": int(result['errcode']), "message": result['msg'], "data": result['data']}}
            return False
        else:
            logging.warning("Unkown error! \n \t %s )" % (str(result)))
            return False
    else:
        logging.warning("Parse error")
        return False


def get_xsrf():
    url = 'http://www.zhihu.com'
    r = urllib2.urlopen(url)
    results = re.compile(
        r"\<input\stype=\"hidden\"\sname=\"_xsrf\"\svalue=\"(\S+)\"", re.DOTALL).findall(r.read())
    if len(results) < 1:
        logging.warning("Extract xsrf code failed")
        return None
    return results[0]


def get_captcha():
    url = 'http://www.zhihu.com/captcha.gif'
    r = urllib2.urlopen(url)
    image_name = 'captcha.'+r.headers['content-type'].split('/')[1]
    with open(image_name, 'wb') as f:
        f.write(r.read())
    return raw_input('Please open image file "%s"\nInput the captcha code: ' % os.path.abspath(image_name))


def islogin():
    # check session
    url = "https://www.zhihu.com/settings/profile"
    r = urllib2.urlopen(url)
    redirect_url = r.geturl()
    return redirect_url == url

if __name__ == '__main__':
    login()
    r = urllib2.urlopen('https://www.zhihu.com/settings/profile').read()
    #open('temp.html', 'wb').write(r)
    full_name = re.compile(
        r'<div class="top-nav-profile">.*?<span class="name">(.*?)</span>', re.DOTALL).search(r).group(1)
    print full_name#.decode('utf-8').encode('gbk')
    avatar_src = re.compile(
        r'<img class="avatar avatar-s".*?src="(.*?)"', re.DOTALL).search(r).group(1)
    r = urllib2.urlopen(avatar_src).read()
    avatar_file = 'avatar.' + avatar_src.split('.')[-1]
    open(avatar_file, 'wb').write(r)
<file_sep># 知乎小工具


* 支持cookie登录