1. 程式人生 > >Python爬取qq空間說說

Python爬取qq空間說說

#coding:utf-8
#!/usr/bin/python3
from selenium import webdriver
import time
import re
import importlib2
import sys
importlib2.reload(sys)

def startSpider():
    driver = webdriver.Chrome('/Users/zachary/zachary/chromedriver.exe') #這個是chormedriver的地址
    driver.get('https://qzone.qq.com/')

    driver.switch_to.frame('login_frame')
    driver.find_element_by_id('switcher_plogin').click()

    driver.find_element_by_id('u').clear()
    driver.find_element_by_id('u').send_keys('QQ號')  #這裡填寫你的QQ號
    driver.find_element_by_id('p').clear()
    driver.find_element_by_id('p').send_keys('QQ密碼')  #這裡填寫你的QQ密碼

    driver.find_element_by_id('login_button').click()
    time.sleep(2)

    #設定爬取內容儲存路徑
    f = open('/Users/zachary/Documents/shuoshuo.txt','w')

    #---------------獲得g_qzonetoken 和 gtk
    html = driver.page_source

    '''g_qzonetoken=re.search('window\.g_qzonetoken = \(function\(\)\{ try\{return (.*?);\} catch\(e\)',html)#從網頁原始碼中提取g_qzonetoken'''
    g_qzonetoken = "e794139a284d6ea9e0b26826e541b55df37d0667a3544f534de25aebdb64628d3ab75e1d7104bbb22a"

    cookie = {}#初始化cookie字典
    for elem in driver.get_cookies():#取cookies
        cookie[elem['name']] = elem['value']

    gtk=getGTK(cookie)#通過getGTK函式計算gtk
    #print(g_qzonetoken)
    #print(gtk)

    #--------------獲得好友列表   注意下面的連結
    driver.get('https://user.qzone.qq.com/proxy/domain/r.qzone.qq.com/cgi-bin/tfriend/friend_hat_get.cgi?hat_seed=1&uin=你的QQ號fupdate=1&g_tk='+str(gtk)+'&qzonetoken='+str(g_qzonetoken)+'&g_tk='+str(gtk))
    friend_list = driver.page_source
    friend_list = str( friend_list )
    abtract_pattern  =  re.compile('\"(.\d*)\":\{\\n"realname":"(.*?)"}',re.S)
    QQ_name_list = re.findall(abtract_pattern,str(friend_list)) #陣列
    print(QQ_name_list)
    numList=dict()# numList => (QQnum:QQname)  #列表
    for i in QQ_name_list:
        numList[str(i[0])]=str(i[1])
    begin = 0
    last_source = ""
    tag = 1
    first = 0
    firstTime=""

    #如果要爬取自己的說說,手動新增自己的qq號
    #numList['你的qq號']='你的名字'
    #print(numList)

    for key in numList.keys():
        QQnum = key
        QQname = numList[QQnum]

        if QQnum == "好友qq號":  #根據qq號查詢指定好友說說
            count = 1
            begin = 0
            while tag==1 :
                #-------------進入好友說說頁面                                                                       #'+QQnum+'              '+str(begin)+'
                #print("Begin:"+str(begin))
                driver.get('https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?uin='+QQnum+'&ftype=0&sort=0&pos='+str(begin)+'&num=40&replynum=200&g_tk='+str(gtk)+'&callback=_preloadCallback&code_version=1&format=jsonp&need_private_comment=1&qzonetoken='+str(g_qzonetoken)+'&g_tk='+str(gtk))

                try:
                    msg_list_json = driver.page_source
                except:
                    begin = begin + 40
                    continue


                msg_list_json = str(msg_list_json)
                if last_source==msg_list_json :
                    break
                else:
                    last_source=msg_list_json

                #檢測是否沒有許可權訪問
                abtract_pattern  =  re.compile(',"message":"(.*?)","name":',re.S)
                message = re.findall(abtract_pattern,str(msg_list_json))
                if message!=[]:
                    if str(message[0])=='對不起,主人設定了保密,您沒有許可權檢視':#對不起,主人設定了保密,您沒有許可權檢視
                        break

                #print(msg_list_json)
                #解析JSON
                #webDriver沒有現成的JSON解析器,所以採用獲取原始碼的方式,然後使用正則表示式獲取具體細節
                msg_list_json =  msg_list_json.split("msglist")[1]#拆分json,縮小範圍,也能加快解析速度
                msg_list_json =  msg_list_json.split("smoothpolicy")[0]
                msg_list_json =  msg_list_json.split("commentlist")[1:]

                #說說動態分4種:1、文字說說(或帶有配圖的文字說說)
                #              2、只有圖片的說說
                #              3、轉發,並配有文字
                #              4、轉發,不配文字

                for text in msg_list_json:
                    # 1、先檢查說說,使用者是否傳送了文字,如果沒有文字,正則表示式匹配無效
                    abtract_pattern  =  re.compile('\}\],"content":"(.*?)","createTime":"(.*?)","created_time":(.*?),"',re.S)
                    msg_time = re.findall(abtract_pattern,str(text))

                    if msg_time!=[]:
                        # 2、如果作者說說有文字,那麼檢查是否有轉發內容
                        msg = str(msg_time[0][0])
                        sendTime = str(msg_time[0][1])

                        abtract_pattern  = re.compile('\}\],"content":"(.*?)"},"rt_createTime":"(.*?)","',re.S)
                        text = text.split("created_time")[1]
                        msg_time2 = re.findall(abtract_pattern,str(text))

                        #合併傳送內容 格式:評論+轉發內容
                        if msg_time2!=[]:
                            msg = msg +"  轉發內容:"+str(msg_time2[0][0])

                    else:
                        # 3、說說內容為空,檢查是否為 =>只有圖片的說說 or 轉發,不配文字
                        #獲取正文傳送時間 (傳送時間分為:正文傳送時間 or 轉發時間)
                        abtract_pattern  =  re.compile('"conlist":null,"content":"","createTime":"(.*?)",',re.S)
                        msgNull_time = re.findall(abtract_pattern,str(text))

                        if msgNull_time!=[]:
                            #如果有正文傳送時間,那麼就是這條說說僅含有圖片  =>只有圖片的說說
                            msg = "圖片"
                            sendTime = str(msgNull_time[0])
                        else:
                            #如果沒有正文傳送時間,那麼就是說這條說為 =>轉發,不配文字
                            abtract_pattern  =  re.compile('\}\],"content":"(.*?)"},"rt_createTime":"(.*?)","',re.S)
                            msg_time = re.findall(abtract_pattern,str(text))
                            msg ="  轉發內容:"+str(msg_time[0][0])
                            sendTime = str(msg_time[0][1])

                    #寫入本地檔案
                    #f.write('{},{},{},{}\n'.format(str(QQname),str(QQnum),sendTime,msg))


                    print(str(count)+" : "+str(QQname)+" : "+str(QQnum)+" : "+sendTime+" : "+msg)
                    count = count + 1

                begin =  begin + 40

def getGTK(cookie):
    hashes = 5381
    for letter in cookie['p_skey']:
        hashes += (hashes << 5) + ord(letter)
    return hashes & 0x7fffffff
startSpider()
print("爬取結束")