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压缩解压缩zip文件及破解zip文件密码的方法
Nov 04 Python
Python数据分析之真实IP请求Pandas详解
Nov 18 Python
Python实现在线暴力破解邮箱账号密码功能示例【测试可用】
Sep 06 Python
python中datetime模块中strftime/strptime函数的使用
Jul 03 Python
Python爬虫常用小技巧之设置代理IP
Sep 13 Python
在Python中定义一个常量的方法
Nov 10 Python
Python文件如何引入?详解引入Python文件步骤
Dec 10 Python
详解python 利用echarts画地图(热力图)(世界地图,省市地图,区县地图)
Aug 06 Python
在Django下测试与调试REST API的方法详解
Aug 29 Python
OpenCV 表盘指针自动读数的示例代码
Apr 10 Python
详解python的变量缓存机制
Jan 24 Python
Python爬虫之爬取某文库文档数据
Apr 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执行shell脚本运行程序不产生core文件的方法
2016/12/28 PHP
PHP编程实现的TCP服务端和客户端功能示例
2018/04/13 PHP
基于jquery的弹出提示框始终处于窗口的居中位置(类似于alert弹出框的效果)
2011/09/28 Javascript
JS TextArea字符串长度限制代码集合
2012/10/31 Javascript
Javascript拓展String方法小结
2013/07/08 Javascript
javascript制作2048游戏
2015/03/30 Javascript
nodejs调用cmd命令实现复制目录
2015/05/04 NodeJs
jquery实现Ctrl+Enter提交表单的方法
2015/07/21 Javascript
基于JQuery实现图片轮播效果(焦点图)
2016/02/02 Javascript
JS访问DOM节点方法详解
2016/11/29 Javascript
简述vue中的config配置
2018/01/23 Javascript
vue js秒转天数小时分钟秒的实例代码
2018/08/08 Javascript
vue项目首屏加载时间优化实战
2019/04/23 Javascript
一起写一个即插即用的Vue Loading插件实现
2019/10/31 Javascript
Element-UI 使用el-row 分栏布局的教程
2020/10/26 Javascript
[01:04:06]DOTA2上海特级锦标赛A组资格赛#2 Secret VS EHOME第一局
2016/02/26 DOTA
python进程管理工具supervisor使用实例
2014/09/17 Python
Python常用时间操作总结【取得当前时间、时间函数、应用等】
2017/05/11 Python
Python中进程和线程的区别详解
2017/10/29 Python
Django ManyToManyField 跨越中间表查询的方法
2018/12/18 Python
Jupyter notebook在mac:linux上的配置和远程访问的方法
2019/01/14 Python
Python生命游戏实现原理及过程解析(附源代码)
2019/08/01 Python
python 实现方阵的对角线遍历示例
2019/11/29 Python
解决Opencv+Python cv2.imshow闪退问题
2020/04/24 Python
如何用Python绘制3D柱形图
2020/09/16 Python
使用css3实现的windows8开机加载动画
2014/12/09 HTML / CSS
5个你不知道的HTML5的接口介绍
2013/08/07 HTML / CSS
微信端html5页面调用分享接口示例
2018/03/14 HTML / CSS
小米俄罗斯授权商店:Xiaomi俄罗斯
2019/12/08 全球购物
空气环保标语
2014/06/12 职场文书
2014年“四风”问题个人整改措施
2014/09/17 职场文书
交通事故赔偿协议书
2014/10/16 职场文书
离退休人员聘用协议书
2014/11/24 职场文书
推广普通话主题班会
2015/08/17 职场文书
《画家和牧童》教学反思
2016/02/17 职场文书
CSS使用SVG实现动态分布的圆环发散路径动画
2022/12/24 HTML / CSS