Python爬取qq空间说说的实例代码


Posted in Python onAugust 17, 2018

具体代码如下所示:

#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("爬取结束")

总结

以上所述是小编给大家介绍的Python爬取qq空间说说的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
Python多进程同步简单实现代码
Apr 27 Python
python enumerate函数的使用方法总结
Nov 15 Python
用xpath获取指定标签下的所有text的实例
Jan 02 Python
python随机在一张图像上截取任意大小图片的方法
Jan 24 Python
200行python代码实现2048游戏
Jul 17 Python
Python 使用 Pillow 模块给图片添加文字水印的方法
Aug 30 Python
深入了解Python在HDA中的应用
Sep 05 Python
Python整数与Numpy数据溢出问题解决
Sep 11 Python
Ubuntu中配置TensorFlow使用环境的方法
Apr 21 Python
PyCharm 2020.2下配置Anaconda环境的方法步骤
Sep 23 Python
Python+Opencv实现把图片、视频互转的示例
Dec 17 Python
python中sqllite插入numpy数组到数据库的实现方法
Jun 21 Python
django进阶之cookie和session的使用示例
Aug 17 #Python
Django 登陆验证码和中间件的实现
Aug 17 #Python
python读取Excel实例详解
Aug 17 #Python
python框架中flask知识点总结
Aug 17 #Python
Flask Web开发入门之文件上传(八)
Aug 17 #Python
python操作excel的方法
Aug 16 #Python
python3调用百度翻译API实现实时翻译
Aug 16 #Python
You might like
无数据库的详细域名查询程序PHP版(1)
2006/10/09 PHP
PHP中Date()时间日期函数的使用方法小结
2011/04/20 PHP
Netbeans 8.2与PHP相关的新特性介绍
2016/10/08 PHP
老生常谈php 正则中的i,m,s,x,e分别表示什么
2017/03/02 PHP
PHP与SQL语句写一句话木马总结
2019/10/11 PHP
HR vs ForZe BO3 第二场 2.13
2021/03/10 DOTA
JQuery 常用方法基础教程
2009/02/06 Javascript
取选中的radio的值
2010/01/11 Javascript
jquery last-child 列表最后一项的样式
2010/01/22 Javascript
解析offsetHeight,clientHeight,scrollHeight之间的区别
2013/11/20 Javascript
jquery实现checkbox 全选/全不选的通用写法
2014/02/22 Javascript
jquery插件jquery.LightBox.js实现点击放大图片并左右点击切换效果(附demo源码下载)
2016/02/25 Javascript
jquery实现input框获取焦点的方法
2017/02/06 Javascript
详解JavaScript 新语法之Class 的私有属性与私有方法
2019/04/23 Javascript
微信小程序实现3D轮播图效果(非swiper组件)
2019/09/21 Javascript
Vue实现兄弟组件间的联动效果
2020/01/21 Javascript
如何在selenium中使用js实现定位
2020/08/18 Javascript
Python实现的HTTP并发测试完整示例
2020/04/23 Python
python中__slots__用法实例
2015/06/04 Python
各个系统下的Python解释器相关安装方法
2015/10/12 Python
win10环境下python3.5安装步骤图文教程
2017/02/03 Python
利用Python在一个文件的头部插入数据的实例
2018/05/02 Python
Python pymongo模块常用操作分析
2018/09/01 Python
Python I/O与进程的详细讲解
2019/03/08 Python
用Python识别人脸,人种等各种信息
2019/07/15 Python
PyQt Qt Designer工具的布局管理详解
2019/08/07 Python
更新升级python和pip版本后不生效的问题解决
2020/04/17 Python
使用tensorflow根据输入更改tensor shape
2020/06/23 Python
美国知名的时尚购物网站:Anthropologie
2016/12/22 全球购物
西班牙在线宠物商店:zooplus.es
2017/02/24 全球购物
知名企业招聘广告词大全
2014/03/18 职场文书
QQ空间主人寄语大全
2014/04/12 职场文书
《微笑着面对生活》优秀演讲稿范文
2014/09/23 职场文书
2015暑期爱心支教策划书
2015/07/14 职场文书
Python基础之教你怎么在M1系统上使用pandas
2021/05/08 Python
java objectUtils 使用可能会出现的问题
2022/02/28 Java/Android