首页 > 代码库 > python获取微信公共平台消息列表和用户头像

python获取微信公共平台消息列表和用户头像

转载需注明原文地址:http://blog.csdn.net/btyh17mxy/article/details/25207889


刚写的模拟登陆的方式从获取微信公众平台消息列表和用户头像的库,之后还会继续增加相关功能,github地址https://github.com/btyh17mxy/wxwall

#!/usr/bin/env python
# coding: UTF-8
import json
import hashlib
import re
import random
import json
import requests
import logging
DEBUG_LEVEL = logging.DEBUG
try:
    import colorizing_stream_handler
    root = logging.getLogger()
    root.setLevel(DEBUG_LEVEL)
    root.addHandler(colorizing_stream_handler.ColorizingStreamHandler())
except Exception, e:
    print ‘can not import colorizing_stream_handler, using logging.StreamHandler()‘
    root = logging.getLogger()
    root.setLevel(DEBUG_LEVEL)
    root.addHandler(logging.StreamHandler())



‘‘‘base exception class.
‘‘‘
class WeixinPublicError(Exception):
    pass



‘‘‘raise when cookies expired.
‘‘‘
class WeixinNeedLoginError(WeixinPublicError):
    pass



‘‘‘rasie when unenable to login.
‘‘‘
class WeixinLoginError(WeixinPublicError):
    pass



class WeixinPublic(object):
    
    def __init__(self, account, pwd, token = None, cookies = None, ifencodepwd = False):
        self.account = account
        if ifencodepwd:
            self.pwd = pwd 
        else:
            self.pwd = hashlib.md5(pwd).hexdigest()
        self.wx_cookies = cookies
        self.lastmsgid = 0 
        self.token = token 

        if self.token == None or self.wx_cookies == None:
            self.token = ‘‘
            self.wx_cookies = ‘‘
            self.login()

    ‘‘‘login to weichat, get token and cookies.

    Raise:
        WeixinLoginError, when can not get token from respond.
    ‘‘‘
    def login(self):
        url = ‘https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN‘
        payload = {
                ‘username‘ : self.account,
                ‘imgcode‘ : ‘‘,
                ‘f‘ : ‘json‘,
                ‘pwd‘ : self.pwd,
                }
        headers = {
                ‘x-requested-with‘ : ‘XMLHttpRequest‘,
                ‘referer‘ : ‘https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN‘,
                }

        r = requests.post(url, data = http://www.mamicode.com/payload, headers = headers)>