python爬取微博评论_python抓取新浪微博评论并分析

1,实现效果

SouthEast

SouthEast

SouthEast

2,数据库

SouthEast

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(']*usercard[^>]*>',page)

for n in range(0,len(pagename)):

pagename[n] = pagename[n].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'

',page)

for t in range(0,len(pagecontent)):

a = pagecontent[t].split("<\/a>")

b = a[len(a)-1]

c = re.sub(r"",'[表情]',b) #去掉图片表情

d = re.sub(r"",'',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):#查看评论最多的前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):#查看某用户评论

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就能方便得下载安装某模块啦~

本人新手菜鸟一只,如果有什么地方没有写好或者写错的地方,欢迎各位红领巾批评指出。所有代码基本都贴出来了,如果有什么疑惑,也很欢迎一起讨论,共同进步

tongue.gif

原文:http://blog.csdn.net/xiaolanzao/article/details/31749621

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
分布式虫是指将任务分散到多个上进行并行处理,以提高效率和速度。下面是一个简单的分布式微博评论的代码示例: 1. 首先,需要安装必要的库,如requests、beautifulsoup等。 2. 创建一个任务队列,用于存放待微博URL。 3. 创建多个虫节点,每个节点从任务队列中获的URL,并进行相应的处理。 4. 在每个节点中,使用requests库发送HTTP请求获微博页面的HTML内容。 5. 使用beautifulsoup库解析HTML内容,提微博评论的相关信息。 6. 将提到的评论信息保存到数据库或文件中。 下面是一个简单的代码示例: ```python import requests from bs4 import BeautifulSoup from multiprocessing import Process, Queue # 定义任务队列 task_queue = Queue() # 定义虫节点 def crawler(): while not task_queue.empty(): url = task_queue.get() response = requests.get(url) html = response.text # 解析HTML内容,提评论信息 soup = BeautifulSoup(html, 'html.parser') comments = soup.find_all('div', class_='comment') for comment in comments: # 提评论内容等信息并保存到数据库或文件中 pass # 添加待微博URL到任务队列 task_queue.put('https://weibo.com/xxxxxx') task_queue.put('https://weibo.com/yyyyyy') # 创建多个虫节点 num_nodes = 4 nodes = [] for i in range(num_nodes): node = Process(target=crawler) nodes.append(node) node.start() # 等待所有节点完成任务 for node in nodes: node.join() ``` 请注意,以上代码只是一个简单示例,实际的分布式虫需要考虑更多的细节,如任务调度、数据去重、异常处理等。另外,微博评论需要注意遵守相关网站的虫规则,以免触发反机制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值