查看: 15235|回复: 5

[Python] 抓取微博示例程序

[复制链接]
  • TA的每日心情
    无聊
    2016-8-19 10:32
  • 签到天数: 80 天

    [LV.6]常住居民II

    发表于 2015-3-3 18:56:56 | 显示全部楼层 |阅读模式
    本帖最后由 xiaoye 于 2015-9-30 11:20 编辑

    由于在做舆情处理,需要大量的数据,所以就出现了这个东西,调用的微博公共API,如果有问题
    查询微博文档
    代码如下:
    1. #encoding = utf8

    2. import weibo
    3. import sys, os, urllib, urllib2
    4. import json
    5. import cookielib
    6. import ConfigParser
    7. import time
    8. import MySQLdb
    9. import re

    10. reload(sys)
    11. sys.setdefaultencoding('utf8')

    12. db_host=""
    13. db_data=""
    14. db_user=""
    15. db_pass=""
    16. db_port=""

    17. APP_KEY="162454*****" #你的APP_KEY
    18. APP_SECRET="753847a8d16ead8a8e7618*****************"#你的app_secret
    19. REDIRECT_URL="https://api.weibo.com/oauth2/default.html"

    20. USER_ID="crawlertest@sina.cn"
    21. USER_PASS="12345*******"
    22. client=weibo.APIClient(APP_KEY,APP_SECRET,REDIRECT_URL)
    23. def make_access_token():
    24.     params = urllib.urlencode({
    25.     'action':'submit',
    26.     'withOfficalFlag':'0',
    27.     'ticket':'',
    28.     'isLoginSina':'',
    29.     'response_type':'code',
    30.     'regCallback':'',
    31.     'redirect_uri':REDIRECT_URL,
    32.     'client_id':APP_KEY,
    33.     'state':'',
    34.     'from':'',
    35.     'userId':USER_ID,
    36.     'passwd':USER_PASS,
    37.     })
    38.     login_url = 'https://api.weibo.com/oauth2/authorize'
    39.     url = client.get_authorize_url()
    40.     content = urllib2.urlopen(url)
    41.     if content:
    42.         headers = { 'Referer' : url }
    43.     request = urllib2.Request(login_url, params, headers)
    44.     opener = get_opener(False)
    45.     urllib2.install_opener(opener)
    46.     try:
    47.         f = opener.open(request)
    48.         return_redirect_uri = f.url
    49.     except urllib2.HTTPError, e:
    50.         return_redirect_uri = e.geturl()
    51.    
    52.     code = return_redirect_uri.split('=')[1]
    53.    
    54.     token = client.request_access_token(code,REDIRECT_URL)
    55.     save_access_token(token)
    56.    
    57. def get_opener(proxy=False):
    58.     rv=urllib2.build_opener(get_cookie(), SmartRedirectHandler())
    59.     rv.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
    60.     return rv

    61. def get_cookie():
    62.     cookies = cookielib.CookieJar()
    63.     return urllib2.HTTPCookieProcessor(cookies)

    64. class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
    65.     def http_error_301(self,cls, req, fp, code, msg, headers):
    66.         result = urllib2.HTTPRedirectHandler.http_error_301(cls, req, fp, code, msg, headers)
    67.         result.status = code
    68.         print headers
    69.         return result

    70.     def http_error_302(self,cls, req, fp, code, msg, headers):
    71.         result = urllib2.HTTPRedirectHandler.http_error_302(cls, req, fp, code, msg, headers)
    72.         result.status = code
    73.         print headers
    74.         return result
    75.    
    76. def save_access_token(token):
    77.     time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    78.     cf=ConfigParser.ConfigParser()
    79.     cf.read("./token.ini")
    80.     cf.set("token","token",token.access_token)
    81.     cf.set("token","expires_in",token.expires_in )
    82.     cf.set("token","data",time)   
    83.     cf.write(open("./token.ini","w"))
    84.    
    85. def apply_access_token():
    86.     cf=ConfigParser.ConfigParser()
    87.     cf.read("./token.ini")
    88.     access_token=cf.get("token","access_token")
    89.     expires_in=cf.get("token","expires_in")
    90.     #print access_token
    91.     #print expires_in
    92.    
    93.     client.set_access_token(access_token, expires_in)
    94.    
    95. def get_public_weibo():
    96.     try:
    97.         text=client.statuses.public_timeline.get()
    98.     except StandardError,e:
    99.         if e.error_code==10023:
    100.             print u"当前账号已经超出使用限制,请稍候再试!"
    101.             exit(0)
    102.         time.sleep(3600)
    103.     js=json.dumps(text)
    104.     js=json.loads(js)
    105.     content=js['statuses']
    106.     lenth=len(content)
    107.     max=js['total_number']
    108.     for i in range(0,lenth-1):
    109.         try:
    110.             source=content[i]["source"]
    111.             source=re.match(r'''<a href="(.+?)" rel="nofollow">(.+?)</a>''',source)
    112.             date=content[i]['created_at']
    113.             mid=content[i]["idstr"]
    114.             text=content[i]['text']
    115.             source=source.group(2)
    116.             reports=content[i]['reposts_count']
    117.             comments=content[i]['comments_count']
    118.             atti=content[i]['attitudes_count']
    119.             uid=content[i]['user']['id']
    120.             nick=content[i]['user']['screen_name']
    121.             loca=content[i]['user']['location']
    122.             deci=content[i]['user']['description']
    123.             gender=content[i]['user']['gender']
    124.             verti=content[i]['user']['verified']
    125.             follws=content[i]['user']['bi_followers_count']
    126.             value=[date.decode(),mid,text,source,reports,comments,atti,uid,nick,loca,deci,gender,verti,follws]
    127.             db_save_info(value)
    128.             print u"插入第%s条数据成功!"%i
    129.         except:
    130.             pass
    131.    

    132.         
    133.         
    134.         
    135.         
    136.         
    137. def db_get_config():
    138.     cf=ConfigParser.ConfigParser()
    139.     cf.read("./token.ini")
    140.     db_host=cf.get("dbinfo", "dbserver")
    141.     db_data=cf.get("dbinfo","db_data")
    142.     db_user=cf.get("dbinfo","db_user")
    143.     db_pass=cf.get("dbinfo","password")
    144.     db_port=cf.get("dbinfo","port")
    145.    

    146. def db_save_info(value):
    147.     #value=['2012','10000000','test','test','2','2','2','32111','fuck','1','1','1','1']
    148.     conn=MySQLdb.connect("127.0.0.1","root","123456",charset="utf8")
    149.     conn.select_db("db_info")
    150.     cursor=conn.cursor()
    151.     cursor.execute("SET NAMES 'utf8'")
    152.     cursor.execute('''insert into weibo_info values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''',value)
    153.     conn.commit()
    154.     cursor.close()

    155.    
    156. def get_db_count():
    157.     conn=MySQLdb.connect("127.0.0.1","root","123456")
    158.     conn.select_db("db_info")
    159.     cursor=conn.cursor()  
    160.     cursor.execute("select count(*) from weibo_info")
    161.     result=cursor.fetchall()
    162.     for i in result:
    163.         result=i[0]
    164.     return result


    165. if __name__=="__main__":
    166.     print u'''
    167. ###################################  
    168. # [url=home.php?mod=space&uid=11566]@Author[/url] iceforce  
    169. # @date 2014-11-17  
    170. ##################################  
    171. #抓取公共微博信息示例
    172. #  
    173. ##################################
    174.             '''
    175.     count=get_db_count()
    176.     apply_access_token()
    177.     for i in range(0,150):
    178.         count1=get_db_count()
    179.         count2=count1-count        
    180.         print u"=======================================第%s次执行,已插入%s条数据============================================="%(i,count2)
    181.         get_public_weibo()

    182.     print u"============================================执行完成!============================================================"

    183.    
    复制代码
    回复

    使用道具 举报

    该用户从未签到

    发表于 2015-6-28 04:02:49 | 显示全部楼层
    学习学习技术,加油!
    回复 支持 反对

    使用道具 举报

    该用户从未签到

    发表于 2015-6-30 01:34:39 | 显示全部楼层
    学习学习技术,加油!
    回复 支持 反对

    使用道具 举报

    该用户从未签到

    发表于 2015-6-30 09:33:06 | 显示全部楼层
    还是不错的哦,顶了
    回复 支持 反对

    使用道具 举报

    该用户从未签到

    发表于 2015-6-30 09:36:19 | 显示全部楼层
    感谢楼主的分享~
    回复 支持 反对

    使用道具 举报

    该用户从未签到

    发表于 2015-7-1 17:29:18 | 显示全部楼层
    支持中国红客联盟(ihonker.org)
    回复 支持 反对

    使用道具 举报

    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    指导单位

    江苏省公安厅

    江苏省通信管理局

    浙江省台州刑侦支队

    DEFCON GROUP 86025

    旗下站点

    邮箱系统

    应急响应中心

    红盟安全

    联系我们

    官方QQ群:112851260

    官方邮箱:security#ihonker.org(#改成@)

    官方核心成员

    Archiver|手机版|小黑屋| ( 苏ICP备2021031567号 )

    GMT+8, 2024-5-17 14:09 , Processed in 0.027460 second(s), 13 queries , Gzip On, MemCache On.

    Powered by ihonker.com

    Copyright © 2015-现在.

  • 返回顶部