`
wbj0110
  • 浏览: 1588303 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

新浪微博小爬虫(转)

阅读更多

一直琢磨着写个爬虫玩,上学期都没实行,于是花了大概一天写了这个东西

       其实半天就把程序调试好了,可是在往mysql数据库里保存数据的时候出了问题

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

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

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

         

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

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

 

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

  209. 大家可以加我个人微信号:scccdgf

     

     

    或者关注soledede的微信公众号:soledede
    微信公众号:
分享到:
评论

相关推荐

    python爬虫新浪微博的爬虫源码.zip

    python爬虫新浪微博的爬虫源码.zippython爬虫新浪微博的爬虫源码.zippython爬虫新浪微博的爬虫源码.zippython爬虫新浪微博的爬虫源码.zippython爬虫新浪微博的爬虫源码.zippython爬虫新浪微博的爬虫源码.zippython...

    python爬虫新浪微博爬虫资料合集.zip

    python爬虫新浪微博爬虫资料合集.zippython爬虫新浪微博爬虫资料合集.zippython爬虫新浪微博爬虫资料合集.zippython爬虫新浪微博爬虫资料合集.zippython爬虫新浪微博爬虫资料合集.zippython爬虫新浪微博爬虫资料合集...

    新浪微博分布式爬虫系统简介.pptx

    最后,该系统在微博爬虫任务优化方面实现了任务拆分和合理时间下发,提高了任务抓取效率。系统爬取结果测试表明,160 万转发列表,125 个并行抓取节点,列表任务完成时间 。 本文档提供了新浪微博分布式爬虫系统的...

    针对于食品安全的新浪微博爬虫源码.zip

    针对于食品安全的新浪微博爬虫源码.zip针对于食品安全的新浪微博爬虫源码.zip针对于食品安全的新浪微博爬虫源码.zip针对于食品安全的新浪微博爬虫源码.zip针对于食品安全的新浪微博爬虫源码.zip针对于食品安全的新浪...

    新浪微博话题爬虫

    本项目是关于“新浪微博话题爬虫”的实现,主要使用C#编程语言完成,开发者通过Visual Studio 2010(VS2010)进行开发。爬虫技术在大数据时代扮演着重要的角色,它能有效地抓取互联网上的信息,而新浪微博作为中国...

    基于Python的新浪微博数据爬虫

    基于Python的新浪微博数据爬虫_周中华基于Python的新浪微博数据爬虫_周中华

    新浪微博python爬虫程序

    这是一个用于在新浪微博平台上进行内容抓取的Python爬虫程序。通过该程序,用户可以自动获取新浪微博上的用户信息、微博内容、评论等数据,实现批量采集和分析新浪微博内容的目的。 该爬虫程序主要利用Python中一些...

    新浪微博爬虫,用python爬取新浪微博数据.zip

    【标题】:“新浪微博爬虫,用python爬取新浪微博数据” 【描述】:“此项目是关于如何使用Python编程语言构建一个爬虫,以抓取并分析新浪微博上的数据。爬虫技术在大数据时代对于获取社交媒体信息、进行网络数据...

    基于Python的新浪微博数据爬虫.pdf

    标题中提到的“基于Python的新浪微博数据爬虫”涉及了开发一种爬虫工具,该工具专门用于爬取新浪微博平台上的数据。新浪微博作为中国最流行的社交平台之一,拥有庞大的用户群体和丰富的数据信息,这对于社交网络研究...

    新浪微博网络爬虫.rar

    【标题】:“新浪微博网络爬虫.rar”所涉及的知识点主要集中在网络爬虫技术和微博数据的抓取上。网络爬虫,又称网页蜘蛛或网络机器人,是一种自动浏览互联网并抓取网页信息的程序。在本案例中,我们关注的是针对新浪...

    基于python爬取新浪微博爬虫以及生成词云源码.zip

    基于python爬取新浪微博爬虫以及生成词云源码.zip基于python爬取新浪微博爬虫以及生成词云源码.zip基于python爬取新浪微博爬虫以及生成词云源码.zip基于python爬取新浪微博爬虫以及生成词云源码.zip基于python爬取...

    python新浪微博爬虫,爬取微博和用户信息 (源码)

    这是新浪微博爬虫,采用python+selenium实现。 免费资源,希望对你有所帮助,虽然是傻瓜式爬虫,但是至少能运行。同时rar中包括源码及爬取的示例。 参考我的文章: ...[python爬虫] Selenium爬取新浪微博内容及用户...

    新浪微博爬虫,用python爬取新浪微博数据,并下载微博图片和微博视频.zip

    在本资源中,我们主要探讨的是如何利用Python编程语言实现一个针对新浪微博的网络爬虫,目的是抓取微博数据,包括微博的文字内容、图片以及视频。爬虫是数据挖掘的重要工具,它能自动化地从互联网上收集信息,对于...

    新浪微博图片爬虫

    【标题】:“新浪微博图片爬虫” 【描述】:“需要一个微博账号” 【标签】:“python 图片爬虫 scrapy” 在IT行业中,网络爬虫是一种自动化技术,用于从互联网上抓取大量数据。在这个特定的场景中,我们关注的是...

    新浪微博python爬虫程序.zip

    【标题】:“新浪微博python爬虫程序.zip”是一个包含Python编程语言编写的爬虫程序,用于抓取新浪微博上的数据。这个压缩包可能包含了实现这一功能的所有必要文件和代码,旨在帮助用户自动化地收集和分析微博平台上...

    新浪微博爬虫,用python爬取新浪微博数据

    本程序可以连续爬取一个或多个新浪微博用户(如胡歌、迪丽热巴、郭碧婷)的数据,并将结果信息写入文件或数据库。写入信息几乎包括用户微博的所有数据,包括用户信息和微博信息两大类。因为内容太多,这里不再赘述,...

    基于Python的新浪微博数据爬虫.zip

    在本文中,我们将深入探讨如何使用Python来构建一个新浪微博数据爬虫。首先,我们需要了解爬虫的基本原理,然后学习Python中的相关库和技术,最后通过实际案例解析如何实现这个项目。 一、爬虫基础 爬虫是一种自动...

Global site tag (gtag.js) - Google Analytics