溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python如何爬取qq空間說(shuō)說(shuō)

發(fā)布時(shí)間:2021-07-22 11:03:40 來(lái)源:億速云 閱讀:136 作者:小新 欄目:開(kāi)發(fā)技術(shù)

小編給大家分享一下Python如何爬取qq空間說(shuō)說(shuō),相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

具體代碼如下所示:

#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') #這個(gè)是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號(hào)') #這里填寫(xiě)你的QQ號(hào)
  driver.find_element_by_id('p').clear()
  driver.find_element_by_id('p').send_keys('QQ密碼') #這里填寫(xiě)你的QQ密碼
  driver.find_element_by_id('login_button').click()
  time.sleep(2)
  #設(shè)置爬取內(nèi)容保存路徑
  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)#從網(wǎng)頁(yè)源碼中提取g_qzonetoken'''
  g_qzonetoken = "e794139a284d6ea9e0b26826e541b55df37d0667a3544f534de25aebdb64628d3ab75e1d7104bbb22a"
  cookie = {}#初始化cookie字典
  for elem in driver.get_cookies():#取cookies
    cookie[elem['name']] = elem['value']
  gtk=getGTK(cookie)#通過(guò)getGTK函數(shù)計(jì)算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號(hào)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)) #數(shù)組
  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=""
  #如果要爬取自己的說(shuō)說(shuō),手動(dòng)添加自己的qq號(hào)
  #numList['你的qq號(hào)']='你的名字'
  #print(numList)
  for key in numList.keys():
    QQnum = key
    QQname = numList[QQnum]
    if QQnum == "好友qq號(hào)": #根據(jù)qq號(hào)查找指定好友說(shuō)說(shuō)
      count = 1
      begin = 0
      while tag==1 :
        #-------------進(jìn)入好友說(shuō)說(shuō)頁(yè)面                                    #'+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
        #檢測(cè)是否沒(méi)有權(quán)限訪問(wèn)
        abtract_pattern = re.compile(',"message":"(.*?)","name":',re.S)
        message = re.findall(abtract_pattern,str(msg_list_json))
        if message!=[]:
          if str(message[0])=='對(duì)不起,主人設(shè)置了保密,您沒(méi)有權(quán)限查看':#對(duì)不起,主人設(shè)置了保密,您沒(méi)有權(quán)限查看
            break
        #print(msg_list_json)
        #解析JSON
        #webDriver沒(méi)有現(xiàn)成的JSON解析器,所以采用獲取源碼的方式,然后使用正則表達(dá)式獲取具體細(xì)節(jié)
        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:]
        #說(shuō)說(shuō)動(dòng)態(tài)分4種:1、文字說(shuō)說(shuō)(或帶有配圖的文字說(shuō)說(shuō))
        #       2、只有圖片的說(shuō)說(shuō)
        #       3、轉(zhuǎn)發(fā),并配有文字
        #       4、轉(zhuǎn)發(fā),不配文字
        for text in msg_list_json:
          # 1、先檢查說(shuō)說(shuō),用戶是否發(fā)送了文字,如果沒(méi)有文字,正則表達(dá)式匹配無(wú)效
          abtract_pattern = re.compile('\}\],"content":"(.*?)","createTime":"(.*?)","created_time":(.*?),"',re.S)
          msg_time = re.findall(abtract_pattern,str(text))
          if msg_time!=[]:
            # 2、如果作者說(shuō)說(shuō)有文字,那么檢查是否有轉(zhuǎn)發(fā)內(nèi)容
            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))
            #合并發(fā)送內(nèi)容 格式:評(píng)論+轉(zhuǎn)發(fā)內(nèi)容
            if msg_time2!=[]:
              msg = msg +" 轉(zhuǎn)發(fā)內(nèi)容:"+str(msg_time2[0][0])
          else:
            # 3、說(shuō)說(shuō)內(nèi)容為空,檢查是否為 =>只有圖片的說(shuō)說(shuō) or 轉(zhuǎn)發(fā),不配文字
            #獲取正文發(fā)送時(shí)間 (發(fā)送時(shí)間分為:正文發(fā)送時(shí)間 or 轉(zhuǎn)發(fā)時(shí)間)
            abtract_pattern = re.compile('"conlist":null,"content":"","createTime":"(.*?)",',re.S)
            msgNull_time = re.findall(abtract_pattern,str(text))
            if msgNull_time!=[]:
              #如果有正文發(fā)送時(shí)間,那么就是這條說(shuō)說(shuō)僅含有圖片 =>只有圖片的說(shuō)說(shuō)
              msg = "圖片"
              sendTime = str(msgNull_time[0])
            else:
              #如果沒(méi)有正文發(fā)送時(shí)間,那么就是說(shuō)這條說(shuō)為 =>轉(zhuǎn)發(fā),不配文字
              abtract_pattern = re.compile('\}\],"content":"(.*?)"},"rt_createTime":"(.*?)","',re.S)
              msg_time = re.findall(abtract_pattern,str(text))
              msg =" 轉(zhuǎn)發(fā)內(nèi)容:"+str(msg_time[0][0])
              sendTime = str(msg_time[0][1])
          #寫(xiě)入本地文件
          #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("爬取結(jié)束")

以上是“Python如何爬取qq空間說(shuō)說(shuō)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI