对于QQ空间的数据一直来是垂涎不已,老早就想偷过来研究研究,这几天闲下来便开始动手。。。

整个程序的流程为:登录-->获取cookie-->获取所有的好友qq_number-->根据所有的好友qq遍历他们的说说-->get所有好友的说说数据

程序跑了20多分钟就跑完了,,共282好友,,跑了60000+说说

有些个人隐私我抹掉了。。甭介意。嘿嘿

1.登录-->获取cookie

打开http://i.qq.com/,如下图

但大多数时候是这样的

我们这里使用账号密码登录,为了方便使用selenium自动化神器(关于selenium的用法可以参考https://my.oschina.net/u/3264690/blog/899229,这里不做过多阐述)

QQ账号,QQ密码存储在userinfo.ini文件中,然后用configparser将其读取出来

读取的代码如下

configparser是一个读取配置文件的库,这里读取的格式为get('[配置文件中括号里的值]',‘相对应的key值’)

import configparser
config = configparser.ConfigParser(allow_no_value=False)
config.read('userinfo.ini')
self.__username =config.get('qq_info','qq_number')
self.__password=config.get('qq_info','qq_password')

用户信息读取出来后就可以登录了

有些盆友用selenium的时候,可能会发现有些元素定位不到,这是因为有些网页套了一个iFrame

selenium根据id定位到该iframe

self.web.switch_to_frame('login_frame')

自动登录且获取cookie的代码

    def login(self):
self.web.switch_to_frame('login_frame')
log=self.web.find_element_by_id("switcher_plogin")
log.click()
time.sleep(1)
username=self.web.find_element_by_id('u')
username.send_keys(self.__username)
ps=self.web.find_element_by_id('p')
ps.send_keys(self.__password)
btn=self.web.find_element_by_id('login_button')
time.sleep(1)
btn.click()
time.sleep(2)
self.web.get('https://user.qzone.qq.com/{}'.format(self.__username))
cookie=''
for elem in self.web.get_cookies():
cookie+=elem["name"]+"="+ elem["value"]+";"
self.cookies=cookie
self.get_g_tk()
self.headers['Cookie']=self.cookies
self.web.quit()

2.获取所有好友的QQ_number

研究好久后发现在QQ空间主页中权限设置页面中,点击仅限QQ好友,会有下面这样的页面出来

按F12后研究js文件发现有这样一个文件

这个js文件里有好友的qq_number

于是请求这个文件得到qq_number

    def get_frends_url(self):
url='https://h5.qzone.qq.com/proxy/domain/base.qzone.qq.com/cgi-bin/right/get_entryuinlist.cgi?'
params = {"uin": self.__username,
"fupdate": 1,
"action": 1,
"g_tk": self.g_tk}
url = url + parse.urlencode(params)
return url def get_frends_num(self):
t=True
offset=0
url=self.get_frends_url()
while(t):
url_=url+'&offset='+str(offset)
page=self.req.get(url=url_,headers=self.headers)
if "\"uinlist\":[]" in page.text:
t=False
else: if not os.path.exists("./frends/"):
os.mkdir("frends/")
with open('./frends/'+str(offset)+'.json','w',encoding='utf-8') as w:
w.write(page.text)
offset += 50

这里有一个函数self.g_tk()它返回一个加密的p_skey , 在这个js文件中qzfl_v8_2.1.61.js,有这样一段代码

  QZFL.pluginsDefine.getACSRFToken = function(url) {
url = QZFL.util.URI(url);
var skey;
if (url) {
if (url.host && url.host.indexOf("qzone.qq.com") > 0) {
try {
skey = parent.QZFL.cookie.get("p_skey");
} catch (err) {
skey = QZFL.cookie.get("p_skey");
}
} else {
if (url.host && url.host.indexOf("qq.com") > 0) {
skey = QZFL.cookie.get("skey");
}
}
}
if (!skey) {
skey = QZFL.cookie.get("p_skey") || (QZFL.cookie.get("skey") || (QZFL.cookie.get("rv2") || ""));
}
return arguments.callee._DJB(skey);
};
QZFL.pluginsDefine.getACSRFToken._DJB = function(str) {
var hash = 5381;
for (var i = 0, len = str.length;i < len;++i) {
hash += (hash << 5) + str.charCodeAt(i);
}
return hash & 2147483647;
};

把它写成python版的如下

    def get_g_tk(self):
p_skey = self.cookies[self.cookies.find('p_skey=')+7: self.cookies.find(';', self.cookies.find('p_skey='))]
h=5381
for i in p_skey:
h+=(h<<5)+ord(i)
print('g_tk',h&2147483647)
self.g_tk=h&2147483647

因为将好友信息存储为json文件,因此需要解析文件信息

#coding:utf-8
import json
import os
def get_Frends_list():
k = 0
file_list=[i for i in os.listdir('./frends/') if i.endswith('json')]
frends_list=[]
for f in file_list:
with open('./frends/{}'.format(f),'r',encoding='utf-8') as w:
data=w.read()[95:-5]
js=json.loads(data)
# print(js)
for i in js:
k+=1
frends_list.append(i)
return frends_list frends_list=get_Frends_list()
print(frends_list)

3.获取所有好友说说

与之前类似,进入好友的说说主页后发现也有这样一个js文件将所有说说以json形式显示出来

类似的,写了获取说说的代码(经过测试,参数中的num最好写20,否则会出现未知的结果。。。)

    def get_mood_url(self):
url='https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?'
params = {
"sort":0,
"start":0,
"num":20,
"cgi_host": "http://taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6",
"replynum":100,
"callback":"_preloadCallback",
"code_version":1,
"inCharset": "utf-8",
"outCharset": "utf-8",
"notice": 0,
"format":"jsonp",
"need_private_comment":1,
"g_tk": self.g_tk
}
url = url + parse.urlencode(params)
return url def get_mood_detail(self):
from getFrends import frends_list
url = self.get_mood_url()
for u in frends_list[245:]:
t = True
QQ_number=u['data']
url_ = url + '&uin=' + str(QQ_number)
pos = 0
while (t):
url__ = url_ + '&pos=' + str(pos)
mood_detail = self.req.get(url=url__, headers=self.headers)
print(QQ_number,u['label'],pos)
if "\"msglist\":null" in mood_detail.text or "\"message\":\"对不起,主人设置了保密,您没有权限查看\"" in mood_detail.text:
t = False
else:
if not os.path.exists("./mood_detail/"):
os.mkdir("mood_detail/")
if not os.path.exists("./mood_detail/"+u['label']):
os.mkdir("mood_detail/"+u['label'])
with open('./mood_detail/'+u['label']+"/" +str(QQ_number)+"_"+ str(pos) + '.json', 'w',encoding='utf-8') as w:
w.write(mood_detail.text)
pos += 20
time.sleep(2)

将需要的说说数据存入数据库

#存入数据库
def dataToMysql():
con=pymysql.connect(
host='127.0.0.1',
user='root',
password="×××",
database='qq_z',
port=3306,
)
cur=con.cursor()
sql="insert into info (qq_number,created_time,content,commentlist,source_name,cmtnum,name) values ({},{},{},{},{},{},{});" d=[i for i in os.listdir('mood_detail') if not i.endswith('.xls')]
for ii in d:
fl=[i for i in os.listdir('mood_detail/'+ii) if i.endswith('.json')]
print('mood_detail/'+ii)
k=1
for i in fl:
with open('mood_detail/'+ii+"/"+i,'r',encoding='latin-1') as w:
s=w.read()[17:-2]
js=json.loads(s)
print(i)
for s in js['msglist']:
m=-1
if not s['commentlist']:
s['commentlist']=list()
cur.execute(sql.format(int(i[:i.find('_')]),s['created_time'],str(s['content']),str([(x['content'],x['createTime2'],x['name'],x['uin']) for x in list(s['commentlist'])]),str(s['source_name']),int(s['cmtnum']),str(s['name'])))
k+=1
con.commit()
con.close()

将需要的说说数据存入Excel

def dataToExcel():
d=[i for i in os.listdir('mood_detail') if not i.endswith('.xls')]
for ii in d:
wb=xlwt.Workbook()
sheet=wb.add_sheet('sheet1',cell_overwrite_ok=True)
sheet.write(0,0,'content')
sheet.write(0,1,'createTime')
sheet.write(0,2,'commentlist')
sheet.write(0,3,'source_name')
sheet.write(0,4,'cmtnum')
fl=[i for i in os.listdir('mood_detail/'+ii) if i.endswith('.json')]
print('mood_detail/'+ii)
k=1
for i in fl:
with open('mood_detail/'+ii+"/"+i,'r',encoding='latin-1') as w:
s=w.read()[17:-2]
js=json.loads(s)
print(i)
for s in js['msglist']:
m=-1
sheet.write(k,m+1,str(s['content']))
sheet.write(k,m+2,str(s['createTime']))
if not s['commentlist']:
s['commentlist']=list()
sheet.write(k,m+3,str([(x['content'],x['createTime2'],x['name'],x['uin']) for x in list(s['commentlist'])]))
sheet.write(k,m+4,str(s['source_name']))
sheet.write(k,m+5,str(s['cmtnum']))
k+=1
if not os.path.exists('mood_detail/Excel/'):
os.mkdir('mood_detail/Excel/')
try:
wb.save('mood_detail/Excel/'+ii+'.xls')
except Exception:
print("error")

4.分析数据

24小时发布的说说数

大家在中午和晚上发布的说说比较多,凌晨比较少

说说最多排行top20

说说最少排行top20

果然,,闷骚的人发的说说比较多。。。哈哈哈

从2000年到2018年,说说分布如下

看来我的朋友们年轻的时候蛮闷骚,,随着年纪增大,,说说越来越少。。

感谢https://zhuanlan.zhihu.com/p/24656161给我的提示。。。少走了许多弯路

数据抓取速度贼快,,20分钟抓取了我所有好友(282+)60000+说说。。

项目已传到

码云 : https://git.oschina.net/nanxun/QQ_zone.git

github : https://github.com/nanxung/QQ_zone.git

朋友们,觉得有用来个star噢。。蟹蟹。。。

抓取60000+QQ空间说说做一次数据分析的更多相关文章

  1. C#使用Selenium实现QQ空间数据抓取 登录QQ空间

    经@吃西瓜的星星提醒 首先我们介绍下Selenium Selenium也是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE.Mo ...

  2. 360浏览器7.1抓触屏QQ空间包

  3. 通过Scrapy抓取QQ空间

    毕业设计题目就是用Scrapy抓取QQ空间的数据,最近毕业设计弄完了,来总结以下: 首先是模拟登录的问题: 由于Tencent对模拟登录比较讨厌,各个防备,而本人能力有限,所以做的最简单的,手动登录后 ...

  4. python爬虫(一)_爬虫原理和数据抓取

    本篇将开始介绍Python原理,更多内容请参考:Python学习指南 为什么要做爬虫 著名的革命家.思想家.政治家.战略家.社会改革的主要领导人物马云曾经在2015年提到由IT转到DT,何谓DT,DT ...

  5. arpspoof+driftnet+ ARP欺骗简单图片抓取

    arpspoof+driftnet+ ARP欺骗简单图片抓取 driftnet是一款简单而使用的图片捕获工具,可以很方便的在网络数据包中抓取图片.该工具可以实时和离线捕获指定数据包中是图片 环境 受害 ...

  6. [原创.数据可视化系列之十二]使用 nodejs通过async await建立同步数据抓取

    做数据分析和可视化工作,最重要的一点就是数据抓取工作,之前使用Java和python都做过简单的数据抓取,感觉用的很不顺手. 后来用nodejs发现非常不错,通过js就可以进行数据抓取工作,类似jqu ...

  7. Scrapy爬虫框架教程(四)-- 抓取AJAX异步加载网页

    欢迎关注博主主页,学习python视频资源,还有大量免费python经典文章 sklearn实战-乳腺癌细胞数据挖掘 https://study.163.com/course/introduction ...

  8. shell脚本抓取网页信息

    利用shell脚本分析网站数据 # define url time=$(date +%F) mtime=$(date +%T) file=/abc/shell/abc/abc_$time.log ht ...

  9. QQ空间认证之数据篇

    最近,我们发现可以利用开通企鹅媒体平台的方式开通QQ公众号从而绑定我们的QQ号,这样我们所绑定的QQ号就成了认证空间了. 虽说这样很快捷的就认证了我们的QQ空间,但是,起有利也有弊.任何事情都不是十全 ...

随机推荐

  1. 对jsp的初步了解及生成war包(一)

    1.jsp与html的区别 最简单的说:jsp是动态网页,html是静态网页 HTML(Hypertext Markup Language)文本标记语言,它是静态页面,和JavaScript一样解释性 ...

  2. Python模块之subprocess--使用Popen来调用系统命令

    当我们需要调用系统的命令的时候,最先考虑的os 模块.用os.system()和os.popen()来进行操作.但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命 令的输 ...

  3. 浅谈WEB编辑器——HBuilder

    我自己用过的WEB编辑器有两种:HBuilder和Dreamweaver.这两种编辑器各有各的特点,但是相对来说,我倾向于前者:后者给我的感觉就是功能繁杂,运行起来慢,而且编码的便捷度不高,时不时需要 ...

  4. hive集成sentry的sql使用语法

    Sentry权限控制通过Beeline(Hiveserver2 SQL 命令行接口)输入Grant 和 Revoke语句来配置.语法跟现在的一些主流的关系数据库很相似.需要注意的是:当sentry服务 ...

  5. UML中关联(Association)和依赖(Dependency)的区别

    原文转自:http://blog.csdn.net/metasearch/article/details/2334853 在UMLCHINA精华区,看到了一些关联和依赖的讨论,似乎越讲越糊涂.我想谈一 ...

  6. ionic搭建与基础

    ionic搭建与基础 一.环境搭建 安装 npm install -g cordova npm install -g ionic 创建 项目 ionic start MyProject blank i ...

  7. c# MySqlHelper_ExecuteSqlTran

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Text;u ...

  8. 利用powershell反弹shell到metasploit

    一.使用msfvenom生成PS1文件: msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST= -f psh-reflection >.p ...

  9. 获取子物体数量---Transform.childCount

    如何判断一个物体下是否有子物体?getchild(0)!=null?显然不可取 那去获取拿到子物体数量?transform.GetChildCount();可以解决 但在新版本中已被弃用,可用tran ...

  10. JAVA金额按比例分摊,零头处理

    金额精确计算,必须使用BigDecimal; 平均分摊,分摊的零头,一般都是由数据"精度"和分摊系数决定的: 主要是如何对零头进行处理,保证尽可能的平均分配. 1.按户均摊 /** ...