python抓取新浪微博评论并分析
2014-06-17 12:36
351 查看
1,实现效果
![](https://oscdn.geek-share.com/Uploads/Images/Content/201910/07/9626b354e451126e810e8ab8bd521e97)
![](https://oscdn.geek-share.com/Uploads/Images/Content/201910/07/ebcd8eb2fd4138223ceef5449288c7b5)
![](https://oscdn.geek-share.com/Uploads/Images/Content/201910/07/1fb0f5f2b0bdfd00c450267c446ccfb4)
2,数据库
![](https://oscdn.geek-share.com/Uploads/Images/Content/201910/07/ea22a26db2eefc0f286e541476c23e59)
3,主要步骤
1,输入账号密码,模拟新浪微博登陆
2,抓取评论页的内容
3,用正则表达式过滤出用户名,评论时间和评论内容
4,将得到的内容存入数据库
5,用SQL语句实现其他功能:例如统计评论次数等
4,详细步骤
# -*- coding: utf-8 -*-
import requests
import base64
import re
import urllib
import rsa
import json
import binascii
import MySQLdb
class Userlogin:
def userlogin(self,username,password,pagecount):
session = requests.Session()
url_prelogin = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.5)&_=1364875106625'
url_login = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.5)'
#get servertime,nonce, pubkey,rsakv
resp = session.get(url_prelogin)
json_data = re.search('\((.*)\)', resp.content).group(1)
data = json.loads(json_data)
servertime = data['servertime']
nonce = data['nonce']
pubkey = data['pubkey']
rsakv = data['rsakv']
# calculate su
su = base64.b64encode(urllib.quote(username))
#calculate sp
rsaPublickey= int(pubkey,16)
key = rsa.PublicKey(rsaPublickey,65537)
message = str(servertime) +'\t' + str(nonce) + '\n' + str(password)
sp = binascii.b2a_hex(rsa.encrypt(message,key))
postdata = {
'entry': 'weibo',
'gateway': '1',
'from': '',
'savestate': '7',
'userticket': '1',
'ssosimplelogin': '1',
'vsnf': '1',
'vsnval': '',
'su': su,
'service': 'miniblog',
'servertime': servertime,
'nonce': nonce,
'pwencode': 'rsa2',
'sp': sp,
'encoding': 'UTF-8',
'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
'returntype': 'META',
'rsakv' : rsakv,
}
resp = session.post(url_login,data=postdata)
# print resp.headers
login_url = re.findall('replace\(\'(.*)\'\)',resp.content)
#
respo = session.get(login_url[0])
uid = re.findall('"uniqueid":"(\d+)",',respo.content)[0]
url = "http://weibo.com/u/"+uid
respo = session.get(url)
# print respo.content #获取首页的内容html
#以上为成功登陆微博
#获取数据库连接
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='weiboanalysis',charset='utf8')
curs = conn.cursor()
curs.execute('delete from outbox')
myheaders={}
myheaders['set-cookie'] = resp.headers['set-cookie']
myheaders['Referer'] = 'http://weibo.com/comment/inbox?leftnav=1&wvr=5'
# print myheaders
#以下是开始抓取信息
for i in range(1,int(pagecount)+1):
forwardUrl = """http://weibo.com/comment/inbox?topnav=1&wvr=5&f=1&page=%d"""%i
r = session.post(forwardUrl,headers=myheaders)
page = r.content
# print page
#获取并过滤出用户名,存在pagename数组
pagename = re.findall('<a\s*title=[^>]*usercard[^>]*>',page)
for n in range(0,len(pagename)):
pagename
= pagename
.split('\\"')[1]
#获取并过滤出评论时间,存在pagetime数组
pagetime = re.findall('WB_time S_func2[^>]*>[^>]*>',page)
for t in range(0,len(pagetime)):
pagetime[t] = pagetime[t].split('>')[1].split('<')[0]
#获取并过滤出评论内容,存在pagecont数组
pagecont={}
pagecontent = re.findall(r'<p class=\\\"detail\\(.*?)<\\\/p>',page)
for t in range(0,len(pagecontent)):
a = pagecontent[t].split("<\/a>")
b = a[len(a)-1]
c = re.sub(r"<img(.*?)>",'[表情]',b) #去掉图片表情
d = re.sub(r"<span(.*?)span>",'',c)
pagecont[t] = re.sub(r"\\t|:|:",'',d) #去掉最后的/t和最前的冒号
for index in range(0,len(pagetime)):
sql = """ insert into outbox(uname,time,text) values('%s','%s','%s')"""%(pagename[index],pagetime[index],pagecont[index])
curs.execute(sql)
conn.commit()
curs.close()
conn.close()
从数据库获取评论并分析:
# -*- encoding:utf-8 -*-
__author__ = 'lanzao'
import MySQLdb
class OutboxAnalysis:
def getMost(self,num):<span style="white-space:pre"> </span>#查看评论最多的前num个人
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='weiboanalysis',charset='utf8')
curs = conn.cursor()
sql="""
select uid,uname,count(uname) as count
from outbox
group by uname
order by count(uname) desc
limit %d;
"""% int(num)
curs.execute(sql)
conn.commit()
print "******************评论次数排行榜************************"
for item in curs.fetchall():
print item[1]+" ",str(item[2])+"次"
print "*******************************************************"
curs.close()
conn.close()
def getUser(self,user):<span style="white-space:pre"> </span>#查看某用户评论
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='weiboanalysis',charset='utf8')
curs = conn.cursor()
curs.execute("""select * from outbox where uname='%s'"""%user)
print "*****************************************"
for item in curs.fetchall():
print item[1]+" ",item[2]+" ",item[3]
print "*****************************************"
curs.close()
conn.close()
程序入口:
# -*- encoding:utf-8 -*-
__author__ = 'lanzao'
from OutboxAnalysis import OutboxAnalysis
from UserLogin import Userlogin;
def menu():
print"""
选择你想要的功能:
0,退出
1,查询评论数最多的人
2,查询某用户的所有评论
3,登陆微博并抓取评论
"""
def menuChoice():
choice = raw_input("输入你的选择(0/1/2/3):")
while choice != '0':
if choice == '3':
username = raw_input("输入新浪微博账号:")
password = raw_input("输入密码:")
pagecount = raw_input("输入想要抓取评论的页数:")
o = Userlogin()
o.userlogin(username=username,password=password,pagecount=pagecount)
print "抓取完毕"
choice = raw_input("输入你的选择(0/1/2/3):")
elif choice == '1':
num = raw_input("你想查看前几个人?请输入数字:")
o = OutboxAnalysis()
o.getMost(num)
choice = raw_input("输入你的选择(0/1/2/3):")
elif choice == '2':
name = raw_input("你想查看谁的评论:")
o = OutboxAnalysis()
o.getUser(name)
choice = raw_input("输入你的选择(0/1/2/3):")
else:
print """choice=%s"""%choice
print "输入无效"
choice = raw_input("输入你的选择(0/1/2/3):")
menu()
menuChoice()
5,相应模块的安装
import requests
import base64
import re
import urllib
import rsa
import json
import binascii
import MySQLdb
推荐好用的Python的包管理工具:pip
安装PIP的教程网上很多,装好后,直接在CMD的黑窗口里用命令pip install xxx就能方便得下载安装某模块啦~
本人新手菜鸟一只,如果有什么地方没有写好或者写错的地方,欢迎各位红领巾批评指出。所有代码基本都贴出来了,如果有什么疑惑,也很欢迎一起讨论,共同进步
2,数据库
3,主要步骤
1,输入账号密码,模拟新浪微博登陆
2,抓取评论页的内容
3,用正则表达式过滤出用户名,评论时间和评论内容
4,将得到的内容存入数据库
5,用SQL语句实现其他功能:例如统计评论次数等
4,详细步骤
# -*- coding: utf-8 -*-
import requests
import base64
import re
import urllib
import rsa
import json
import binascii
import MySQLdb
class Userlogin:
def userlogin(self,username,password,pagecount):
session = requests.Session()
url_prelogin = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.5)&_=1364875106625'
url_login = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.5)'
#get servertime,nonce, pubkey,rsakv
resp = session.get(url_prelogin)
json_data = re.search('\((.*)\)', resp.content).group(1)
data = json.loads(json_data)
servertime = data['servertime']
nonce = data['nonce']
pubkey = data['pubkey']
rsakv = data['rsakv']
# calculate su
su = base64.b64encode(urllib.quote(username))
#calculate sp
rsaPublickey= int(pubkey,16)
key = rsa.PublicKey(rsaPublickey,65537)
message = str(servertime) +'\t' + str(nonce) + '\n' + str(password)
sp = binascii.b2a_hex(rsa.encrypt(message,key))
postdata = {
'entry': 'weibo',
'gateway': '1',
'from': '',
'savestate': '7',
'userticket': '1',
'ssosimplelogin': '1',
'vsnf': '1',
'vsnval': '',
'su': su,
'service': 'miniblog',
'servertime': servertime,
'nonce': nonce,
'pwencode': 'rsa2',
'sp': sp,
'encoding': 'UTF-8',
'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
'returntype': 'META',
'rsakv' : rsakv,
}
resp = session.post(url_login,data=postdata)
# print resp.headers
login_url = re.findall('replace\(\'(.*)\'\)',resp.content)
#
respo = session.get(login_url[0])
uid = re.findall('"uniqueid":"(\d+)",',respo.content)[0]
url = "http://weibo.com/u/"+uid
respo = session.get(url)
# print respo.content #获取首页的内容html
#以上为成功登陆微博
#获取数据库连接
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='weiboanalysis',charset='utf8')
curs = conn.cursor()
curs.execute('delete from outbox')
myheaders={}
myheaders['set-cookie'] = resp.headers['set-cookie']
myheaders['Referer'] = 'http://weibo.com/comment/inbox?leftnav=1&wvr=5'
# print myheaders
#以下是开始抓取信息
for i in range(1,int(pagecount)+1):
forwardUrl = """http://weibo.com/comment/inbox?topnav=1&wvr=5&f=1&page=%d"""%i
r = session.post(forwardUrl,headers=myheaders)
page = r.content
# print page
#获取并过滤出用户名,存在pagename数组
pagename = re.findall('<a\s*title=[^>]*usercard[^>]*>',page)
for n in range(0,len(pagename)):
pagename
= pagename
.split('\\"')[1]
#获取并过滤出评论时间,存在pagetime数组
pagetime = re.findall('WB_time S_func2[^>]*>[^>]*>',page)
for t in range(0,len(pagetime)):
pagetime[t] = pagetime[t].split('>')[1].split('<')[0]
#获取并过滤出评论内容,存在pagecont数组
pagecont={}
pagecontent = re.findall(r'<p class=\\\"detail\\(.*?)<\\\/p>',page)
for t in range(0,len(pagecontent)):
a = pagecontent[t].split("<\/a>")
b = a[len(a)-1]
c = re.sub(r"<img(.*?)>",'[表情]',b) #去掉图片表情
d = re.sub(r"<span(.*?)span>",'',c)
pagecont[t] = re.sub(r"\\t|:|:",'',d) #去掉最后的/t和最前的冒号
for index in range(0,len(pagetime)):
sql = """ insert into outbox(uname,time,text) values('%s','%s','%s')"""%(pagename[index],pagetime[index],pagecont[index])
curs.execute(sql)
conn.commit()
curs.close()
conn.close()
从数据库获取评论并分析:
# -*- encoding:utf-8 -*-
__author__ = 'lanzao'
import MySQLdb
class OutboxAnalysis:
def getMost(self,num):<span style="white-space:pre"> </span>#查看评论最多的前num个人
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='weiboanalysis',charset='utf8')
curs = conn.cursor()
sql="""
select uid,uname,count(uname) as count
from outbox
group by uname
order by count(uname) desc
limit %d;
"""% int(num)
curs.execute(sql)
conn.commit()
print "******************评论次数排行榜************************"
for item in curs.fetchall():
print item[1]+" ",str(item[2])+"次"
print "*******************************************************"
curs.close()
conn.close()
def getUser(self,user):<span style="white-space:pre"> </span>#查看某用户评论
conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='weiboanalysis',charset='utf8')
curs = conn.cursor()
curs.execute("""select * from outbox where uname='%s'"""%user)
print "*****************************************"
for item in curs.fetchall():
print item[1]+" ",item[2]+" ",item[3]
print "*****************************************"
curs.close()
conn.close()
程序入口:
# -*- encoding:utf-8 -*-
__author__ = 'lanzao'
from OutboxAnalysis import OutboxAnalysis
from UserLogin import Userlogin;
def menu():
print"""
选择你想要的功能:
0,退出
1,查询评论数最多的人
2,查询某用户的所有评论
3,登陆微博并抓取评论
"""
def menuChoice():
choice = raw_input("输入你的选择(0/1/2/3):")
while choice != '0':
if choice == '3':
username = raw_input("输入新浪微博账号:")
password = raw_input("输入密码:")
pagecount = raw_input("输入想要抓取评论的页数:")
o = Userlogin()
o.userlogin(username=username,password=password,pagecount=pagecount)
print "抓取完毕"
choice = raw_input("输入你的选择(0/1/2/3):")
elif choice == '1':
num = raw_input("你想查看前几个人?请输入数字:")
o = OutboxAnalysis()
o.getMost(num)
choice = raw_input("输入你的选择(0/1/2/3):")
elif choice == '2':
name = raw_input("你想查看谁的评论:")
o = OutboxAnalysis()
o.getUser(name)
choice = raw_input("输入你的选择(0/1/2/3):")
else:
print """choice=%s"""%choice
print "输入无效"
choice = raw_input("输入你的选择(0/1/2/3):")
menu()
menuChoice()
5,相应模块的安装
import requests
import base64
import re
import urllib
import rsa
import json
import binascii
import MySQLdb
推荐好用的Python的包管理工具:pip
安装PIP的教程网上很多,装好后,直接在CMD的黑窗口里用命令pip install xxx就能方便得下载安装某模块啦~
本人新手菜鸟一只,如果有什么地方没有写好或者写错的地方,欢迎各位红领巾批评指出。所有代码基本都贴出来了,如果有什么疑惑,也很欢迎一起讨论,共同进步
![](https://oscdn.geek-share.com/Uploads/Images/Content/201705/40da226498c84c92e2ee7e86a0b4fd72.gif)
相关文章推荐
- 《一出好戏》讲述人性,使用Python抓取猫眼近10万条评论并分析,一起揭秘“这出好戏”到底如何?
- [Python] (多线程版本)抓取聚划算页面商品分析页面获取商品信息并以XML格式保存到本地
- Python:通过摄像头抓取图像并自动上传至新浪微博
- Python中网络页面抓取和页面分析
- python登录新浪微博并抓取内容
- python抓取京东价格分析京东商品价格走势
- Python抓取网页内容应用代码分析
- Python 对新浪微博的元素 (Word, Screen Name)的词汇多样性分析
- Python抓取框架 Scrapy 的架构分析
- python beautifulsoup多线程分析抓取网页
- 【Heritrix基础教程之4】开始一个爬虫抓取的全流程代码分析 分类: H3_NUTCH 2014-06-04 20:10 1039人阅读 评论(0) 收藏
- Python:通过摄像头抓取图像并自动上传至新浪微博
- Python中网络页面抓取和页面分析
- Python抓取网页内容应用代码分析
- 用python的curl和lxml来抓取和分析网页内容
- Python抓取框架 Scrapy 的架构分析
- Python中网络页面抓取和页面分析
- 分享:Python使用cookielib和urllib2模拟登陆新浪微博并抓取数据
- #小练习 使用正则抓取oschina博客专区首页数据 分类: python 小练习 正则表达式 2013-11-11 17:22 604人阅读 评论(0) 收藏
- Python 对新浪微博的博文元素 (Word, Screen Name)的频率分析