前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >新浪微博小爬虫

新浪微博小爬虫

作者头像
机器学习AI算法工程
发布2018-03-12 17:37:08
8550
发布2018-03-12 17:37:08
举报

python的中文编码实在是非常麻烦,不光如此,因为有些用户的简介里有一些特殊符号,®或者笑脸之类的,于是在这里纠结了很久,好歹最后是成功了(其实也就是过滤掉了那些特殊符号)

效率来说呢,开始的时候一个小时能采集大概1.4w条微博的用户信息,但是由于我是从每个人的关注列表里采集的,所以很快就会遇到爬到许多已经爬过的用户,所以总的来说效率不是很高,怪不得那个“中国爬盟”要发动群众的力量去爬

而且有些担心爬久了微博账号被封,我也没敢尝试太久,最后爬了5w条用户信息,8w条关系数据,我拿着数据目前也没什么用,所以就这样吧

python没看多久,代码有冗余的地方,其实主要就是三个函数save_user(),creepy_myself(),creepy_others()

具体的就看代码的注释吧,下载提示看文章末尾,和下面的一样(代码有冗余,因为要先爬出来用户的关注数目来计算有多少页)

[python] view plaincopy

  1. #coding=utf8
  2. import urllib2
  3. import re
  4. from BeautifulSoup import *
  5. import MySQLdb
  6. import sys
  7. """
  8. Login to Sina Weibo with cookie
  9. setdefaultencoding 用于对中文编码的处理
  10. """
  11. reload(sys)
  12. sys.setdefaultencoding('utf8')
  13. COOKIE ='你的cookie'
  14. HEADERS = {'cookie': COOKIE}
  15. UID= COOKIE[COOKIE.find('uid')+4:COOKIE.find('uid')+14]
  16. '''''
  17. 尝试连接数据库,以供保存诗句
  18. '''
  19. try:
  20. conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='root',db='weibodata',port=3309,charset='utf8',use_unicode=False)
  21. cur=conn.cursor()
  22. except MySQLdb.Error,e:
  23. print "Mysql Error %d: %s" % (e.args[0], e.args[1])
  24. def save_user(uuid,uid,name,common):
  25. '''''
  26. save_user(uuid,uid,name,common)
  27. 用于保存诗句,uuid->uid是用户关系,uuid关注uid
  28. uid,name,common是将要保存的用户信息
  29. setup.ini中保存有两个数字
  30. 第一个是now我对当前用户的编号
  31. 第二个point是当前正在扫描的用户的编号
  32. 你可以把它们看作是一个队列的两个指针
  33. '''
  34. fileHandle = open ( 'setup.ini','r+');
  35. now=int(fileHandle.readline())+1;
  36. point =int(fileHandle.readline())
  37. print now
  38. #print uuid,uid,name,common
  39. #保存用户关系信息
  40. count=cur.execute('select * from relations where uid1=\''+str(uuid)+'\' and uid2=\''+str(uid)+'\'')
  41. if (count==0):
  42. cur.execute('insert into relations(uid1,uid2)values(\''+\
  43. str(uuid)+'\',\''+str(uid)+'\')')
  44. conn.commit()
  45. count=cur.execute('select * from users where uid=\''+str(uid)+'\'')
  46. #保存用户信息
  47. if (count==0):
  48. cs=common.encode('gbk', 'ignore').decode('gbk', 'ignore').encode('utf-8', 'ignore')
  49. #print cs
  50. cur.execute('insert into users(id,uid,name,common)values(\''+\
  51. str(now)+'\',\''+str(uid)+'\',\''+str(name)+'\',\"'+\
  52. cs +\
  53. '\")')
  54. conn.commit()
  55. fileHandle.close()
  56. fileHandle = open ( 'setup.ini','w');
  57. fileHandle.write(str(now)+'\n'+str(point))
  58. fileHandle.close()
  59. def creepy_myself():
  60. '''''
  61. 这是用来扫描你自己的关注列表的
  62. 我想着得有个开头,所以第一次使用时应调用这个函数为队列添加一些用户再作扩展
  63. '''
  64. uid= COOKIE[COOKIE.find('uid')+4:COOKIE.find('uid')+14]
  65. url = 'http://weibo.com/'+str(uid)+'/myfollow?t=1&page=1'
  66. mainurl='http://weibo.com/'+str(uid)+'/myfollow?t=1&page='
  67. req = urllib2.Request(url, headers=HEADERS)
  68. text = urllib2.urlopen(req).read()
  69. mainSoup=BeautifulSoup(text)
  70. strs=str(mainSoup.find('div','lev2'));
  71. num=int(strs[strs.find('(')+1:strs.find(')')])
  72. lines=text.splitlines()
  73. for line in lines:
  74. if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_relation_myf'):
  75. n = line.find('html":"')
  76. if n > 0:
  77. j = line[n + 7: -12].replace("\\", "")
  78. soup =BeautifulSoup(j)
  79. follows=soup.findAll('div','myfollow_list S_line2 SW_fun')
  80. for follow in follows:
  81. namess=follow.find('ul','info').find('a')['title']
  82. temp_str=str(follow)
  83. uiddd= temp_str[temp_str.find('uid')+4:temp_str.find('&')]
  84. save_user(UID,uiddd,namess,follow.find('div','intro S_txt2').contents[0][6:])
  85. for i in range(2,num/30+1):
  86. url = 'http://weibo.com/2421424850/myfollow?t=1&page='+str(i)
  87. req = urllib2.Request(url, headers=HEADERS)
  88. text = urllib2.urlopen(req).read()
  89. lines=text.splitlines()
  90. for line in lines:
  91. if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_relation_myf'):
  92. n = line.find('html":"')
  93. if n > 0:
  94. j = line[n + 7: -12].replace("\\", "")
  95. soup =BeautifulSoup(j)
  96. follows=soup.findAll('div','myfollow_list S_line2 SW_fun')
  97. for follow in follows:
  98. namess=follow.find('ul','info').find('a')['title']
  99. temp_str=str(follow)
  100. uiddd =temp_str[temp_str.find('uid')+4:temp_str.find('&')]
  101. save_user(UID,uiddd,namess,follow.find('div','intro S_txt2').contents[0][6:])
  102. def creepy_others(uid):
  103. '''''
  104. 扫描制定uid用户的信息
  105. 和上面一样代码有冗余
  106. 因为要先得到这个用户的关注人数,来计算一共有多少页数据
  107. '''
  108. url="http://weibo.com/"+str(uid)+"/follow?page=";
  109. req = urllib2.Request(url, headers=HEADERS)
  110. text = urllib2.urlopen(req).read()
  111. mainSoup=BeautifulSoup(text.strip())
  112. lines=text.splitlines()
  113. num=1
  114. for line in lines:
  115. if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_relation_hisFollow'):
  116. n = line.find('html":"')
  117. if n > 0:
  118. j = line[n + 7: -12].replace("\\n", "")
  119. j = j.replace("\\t","")
  120. j = j.replace("\\",'');
  121. soup=BeautifulSoup(j)
  122. strs=str(soup.find('div','patch_title'))
  123. num=int(strs[strs.find('关注了')+9:strs.find('人</div')]);
  124. follows=soup.findAll('li','clearfix S_line1')
  125. for follow in follows:
  126. temp_str=str(follow)
  127. # print temp_str
  128. temp_uid=temp_str[temp_str.find('uid'):temp_str.find('&')];
  129. temp_soup=BeautifulSoup(temp_str);
  130. temp_fnick=temp_soup.find('div').find('a')['title']
  131. save_user(uid,temp_uid[4:],temp_fnick,str(temp_soup.find('div','info'))[18:-6]);
  132. #print num/20+2
  133. for i in range(2,num/20+1):
  134. urls="http://weibo.com/"+str(uid)+"/follow?page="+str(i);
  135. req = urllib2.Request(urls, headers=HEADERS)
  136. text = urllib2.urlopen(req).read()
  137. lines=text.splitlines()
  138. for line in lines:
  139. if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_relation_hisFollow'):
  140. n = line.find('html":"')
  141. if n > 0:
  142. j = line[n + 7: -12].replace("\\n", "")
  143. j = j.replace("\\t","")
  144. j = j.replace("\\",'');
  145. soup=BeautifulSoup(j)
  146. strs=str(soup.find('div','patch_title'))
  147. num=int(strs[strs.find('关注了')+9:strs.find('人</div')]);
  148. follows=soup.findAll('li','clearfix S_line1')
  149. for follow in follows:
  150. temp_str=str(follow)
  151. # print temp_str
  152. temp_uid=temp_str[temp_str.find('uid'):temp_str.find('&')];
  153. temp_soup=BeautifulSoup(temp_str);
  154. temp_fnick=temp_soup.find('div').find('a')['title']
  155. save_user(uid,temp_uid[4:],temp_fnick,str(temp_soup.find('div','info'))[18:-6]);
  156. if __name__ == '__main__':
  157. #save_user('123','123','ads','212332231')
  158. #creepy_myself()
  159. '''''
  160. 虽然很谨慎地处理了中文编码,但每过一段时间还是会有一些问题
  161. 于是抛掉了所有异常,防止程序中断
  162. '''
  163. while(1):
  164. '''''
  165. 首先取得队列的尾指针,也就是point
  166. 根据point从数据库中找到uid,然后creepy_others(uuid)
  167. '''
  168. fileHandle = open ( 'setup.ini','r+');
  169. now=int(fileHandle.readline());
  170. point =int(fileHandle.readline())+1;
  171. fileHandle.close()
  172. fileHandle = open ( 'setup.ini','w');
  173. fileHandle.write(str(now)+'\n'+str(point))
  174. fileHandle.close()
  175. cur.execute('select uid from users where id=\''+str(point)+'\'')
  176. uuid=cur.fetchone()[0];
  177. if len(uuid)==10:
  178. try:
  179. creepy_others(uuid)
  180. except Exception , e:
  181. pass
  182. cur.close()
  183. conn.close()

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2015-09-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 大数据挖掘DT数据分析 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档