python自動獲取163郵箱的通信錄、收件箱中的寄件人和標題

#-*- coding:UTF-8 -*-
import urllib,urllib2,cookielib
import xml.etree.ElementTree as etree #xml解析類

class Login163:
   #假裝browser
    header = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
    username = ''
    passwd = ''
    cookie = None #cookie對象
    cookiefile = './cookies.dat' #cookie臨時存放地
    user = ''
    address=''
    mail=''
    
    def __init__(self,username,passwd,address,mail):
        self.username = username
        self.passwd = passwd
        self.address=address
        self.mail=mail
        #cookie設置
        self.cookie = cookielib.LWPCookieJar() #自定義cookie存放
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
        urllib2.install_opener(opener)

   #登錄    
    def login(self):       

        #請求參數設置
        postdata = {
            'username':self.username,
            'password':self.passwd,
            'type':1
            }
        postdata = urllib.urlencode(postdata)

        #發起請求
        req = urllib2.Request(
                url='http://reg.163.com/logins.jsp?type=1&product=mail163&url=http://entry.mail.163.com/coremail/fcg/ntesdoor2?lightweight%3D1%26verifycookie%3D1%26language%3D-1%26style%3D1',
                data= postdata,#請求數據
                headers = self.header #請求頭
            )

        result = urllib2.urlopen(req).read()
        result = str(result)
        self.user = self.username.split('@')[0]

        self.cookie.save(self.cookiefile)#保存cookie
        
        if '登陸成功,正在跳轉...' in result:
            flag = True
        else:
            flag = False
           
        return flag

   #獲取通信錄
    def address_list(self):

        #獲取認證sid
        auth = urllib2.Request(
                url='http://entry.mail.163.com/coremail/fcg/ntesdoor2?username='+self.user+'&lightweight=1&verifycookie=1&language=-1&style=1',
                headers = self.header
            )
        auth = urllib2.urlopen(auth).read()
        for i,sid in enumerate(self.cookie):#enumerate()用於同時返數字索引與數值,其實是一個元組:((0,test[0]),(1,test[1]).......)這有點像php裏的foreach 語句的做用
            sid = str(sid)
            if 'sid' in sid:
                sid = sid.split()[1].split('=')[1]
                break
        self.cookie.save(self.cookiefile)
        
        #請求地址
        url = 'http://twebmail.mail.163.com/js4/s?sid='+sid+'&func=global:sequential&showAd=false&userType=browser&uid='+self.username
        #參數設定(var 變量是必須要的,否則就只能看到:<code>S_OK</code><messages/>這類信息)
        #這裏參數也是在firebug下查看的。
        postdata = {
            'func':'global:sequential',
            'showAd':'false',
            'sid':sid,
            'uid':self.username,
            'userType':'browser',
            'var':'<?xml version="1.0"?><object><array name="items"><object><string name="func">pab:searchContacts</string><object name="var"><array name="order"><object><string name="field">FN</string><boolean name="desc">false</boolean><boolean name="ignoreCase">true</boolean></object></array></object></object><object><string name="func">pab:getAllGroups</string></object></array></object>'
            }
        postdata = urllib.urlencode(postdata)
        
        #組裝請求
        req = urllib2.Request(
            url = url,
            data = postdata,
            headers = self.header
            )
        res = urllib2.urlopen(req).read()
        
        #解析XML,轉換成json
        #說明:因爲這樣請求後163給出的是xml格式的數據,
        #爲了返回的數據能方便使用最好是轉爲JSON
        json = []
        tree = etree.fromstring(res)
        obj = None
        for child in tree:
            if child.tag == 'array':
                obj = child            
                break
        #這裏多參考一下,etree元素的方法屬性等,包括attrib,text,tag,getchildren()等
        obj = obj[0].getchildren().pop()
        for child in obj:
            for x in child:
                attr = x.attrib
                if attr['name']== 'EMAIL;PREF':
                    value = {'email':x.text}
                    json.append(value)
        #將通信錄保存在address.txt中
        F=open(self.address+'.txt','w+')           
        for x in json:
            F.write(x['email'])
            F.write('\n')
        F.close()
    
    #獲取收件箱
    def minbox(self):#收件箱,fid爲1,發件箱爲3,草稿箱爲2
        #獲取認證sid
        auth = urllib2.Request(
                url='http://entry.mail.163.com/coremail/fcg/ntesdoor2?username='+self.user+'&lightweight=1&verifycookie=1&language=-1&style=1',
                headers = self.header
            )
        auth = urllib2.urlopen(auth).read()

        for i,sid in enumerate(self.cookie):
            sid = str(sid)
            if 'sid' in sid:
                sid = sid.split()[1].split('=')[1]
                break
        self.cookie.save(self.cookiefile)
        
        #請求地址
        url = 'http://twebmail.mail.163.com/js4/s?sid='+sid+'&func=mbox:listMessages&showAd=false&userType=browser&uid='+self.username
        postdata = {
            'func':'global:sequential',
            'showAd':'false',
            'sid':'qACVwiwOfuumHPdcYqOOUTAjEXNbBeAr',
            'uid':self.username,
            'userType':'browser',
            'var':'<!--?xml version="1.0"?--><object><int name="fid">1</int><string name="order">date</string><boolean name="desc">true</boolean><boolean name="topFirst">false</boolean><int name="start">0</int><int name="limit">20</int></object>'
            }
        postdata = urllib.urlencode(postdata)
        
        #組裝請求
        req = urllib2.Request(
            url = url,
            data = postdata,
            headers = self.header
            )
        res = urllib2.urlopen(req).read()
        
        json = []
        tree = etree.fromstring(res)
        obj = None
        for child in tree:
            if child.tag == 'array':
                obj = child            
                break

        #這裏多參考一下,etree元素的方法屬性等,包括attrib,text,tag,getchildren()等
        obj = obj.getchildren()
        for child in obj:
            for x in child:
                attr = x.attrib
                value=[]
                if attr['name']== 'from':
                    value.append(x.text.encode("utf-8"))
                if attr['name']=='subject':
                    value.append(x.text.encode("utf-8"))
                if len(value)>0:
                    json.extend(value)
        
        F=open(self.mail+'.txt','w+')           
        for x in json:
            F.write(x)
            F.write('\n')
        F.close()
        
#Demo
print("Requesting......\n\n")
login = Login163('jiangkun_001_001@163.com','8602280','youraddressname','yourmailboxname')
flag = login.login()
if flag==True:
    print("Successful landing")
    login.address_list()
    login.minbox()
相關文章
相關標籤/搜索