Esempio n. 1
0
def post_tweet(access_token):
    client = WeiboClient(access_token)
    files = {'pic': open('水墨荷花.png', 'rb')}
    result = client.post("statuses/share.json",
                         data={"status": "测试一下,看看发送成功了嘛"},
                         files=files)
    print("发送结果:", result)
    files.close()
Esempio n. 2
0
def get_tweets(access_token):

    begin_time = time.time()

    client = WeiboClient(access_token)

    request = client.get(suffix="statuses/public_timeline.json")
    jsonData = json.dumps(request, sort_keys=True, indent=2)  #json输出格式化
    print(request, "\n\n\n", jsonData)
    print("获取微博内容花费时间:", time.time() - begin_time)
Esempio n. 3
0
def index():
    if 'uid' in session and 'access_token' in session:
        client = WeiboClient(session['access_token'])
        result = client.get(suffix="statuses/public_timeline.json", params={"count":5})

        user = client.get(suffix="users/show.json", params={'uid': session['uid']})

        if len(result.get('statuses'))>0 :
            data = tv.statuses_to_data(result.get('statuses'))
            #return 'Logged in as %s \n %s' % (escape(session['uid']), result)
            return render_template('index-o.html', data=data, user=user)
        else:
            return render_template('index-o.html', user=user)
    # return redirect(CAclient.authorize_url)
    return render_template('index-o.html')
Esempio n. 4
0
def postweibo():
    # send a test weibo. the posted text will truncated and add a tail

    time = '%s automatically update. ' % datetime.datetime.now()
    # status = request.args.get('t', time)

    if 'access_token' in session and request.method == 'POST':
        # text = request.form['text']
        text = request.get_json().get('text')
        text = text[:200]
        # key = request.form['key']
        key = request.get_json().get('key')
        _ = ts.update(text)
        _ = ts.update(key)
        # ecr = puer.encrypt(key, text)
        token = request.get_json().get('token')
        if not token:
            return jsonify({'error': 'token missing'})

        # if len(ecr) > 122:
        #     ecr = ecr[:122]
        tail = 'https://aishe.org.cn/puer #<%s' % key # must has this end
        sentpost = '%s %s' % (text, tail)
        client = WeiboClient(token)
        result = client.post("statuses/share.json", data={"status":sentpost, "access_token":session['access_token']})
        # result = client.session.post('https://api.weibo.com/2/statuses/update.json', data={"status":"test article test article"})
        return jsonify(result)
    elif 'access_token' in session and request.method == 'GET':
        return '''
            <h2>加密并分享至微博</h2>
            <a>密码1-8常用汉字,正文不超过128字偶数汉字,非汉字会被丢弃</a>
            <form method="post">
            <p><textarea cols=40 rows=10 name=text value='Limit 128 Char' style="background-color:BFCEDC"></textarea>
            <p><input type=text name=key value='密码'>
            <p><input type=submit value=ENCRYPTWB>
        </form>
        '''
    else:
        return redirect(CAclient.authorize_url)
Esempio n. 5
0
def postweibo():
    # send a test weibo. the posted text will truncated and add a tail

    time = '%s automatically update. ' % datetime.datetime.now()
    # status = request.args.get('t', time)

    if 'access_token' in session and request.method == 'POST':
        text = request.form['text']
        text = text[:200]
        key = request.form['key']
        _ = ts.update(text)
        _ = ts.update(key)
        chars = ts.filterchars(text)
        keychar = ts.filterchars(key)
        ecr = ts.encryptext(chars, keychar)

        if len(ecr) > 122:
            ecr = ecr[:122]
        tail = 'https://aishe.org.cn 密码:%s' % keychar # must has this end
        sentpost = '%s %s' % (ecr, tail)
        client = WeiboClient(session['access_token'])
        result = client.post("statuses/share.json", data={"status":sentpost, "access_token":session['access_token']})
        # result = client.session.post('https://api.weibo.com/2/statuses/update.json', data={"status":"test article test article"})
        return jsonify(result)
    elif 'access_token' in session and request.method == 'GET':
        return '''
            <h2>加密并分享至微博</h2>
            <a>密码1-8常用汉字,正文不超过128字偶数汉字,非汉字会被丢弃</a>
            <form method="post">
            <p><textarea cols=40 rows=10 name=text value='Limit 128 Char' style="background-color:BFCEDC"></textarea>
            <p><input type=text name=key value='密码'>
            <p><input type=submit value=ENCRYPTWB>
        </form>
        '''
    else:
        return redirect(url_for('login'))
Esempio n. 6
0
def rate():
    #this parse and visulize the weibo object
    # login protect
    if not 'access_token' in session:
        return redirect(CAclient.authorize_url)
    # construct client, fetch home_timeline
    uid = session['uid']
    user = User(uid, session['access_token'])
    since_id, count = user.last_read()
    client = WeiboClient(session['access_token'])
    result = client.get('statuses/home_timeline.json', params={"since_id": since_id,
                                                                   "count":100})
    # construct uid if needed
    s = result.get('statuses')
    if len(s) > 0:
        newcount = len(s)
        newsince_id = s[0].get('id')
        user.update_read(newsince_id, newcount)
    # use preconfigured default app logger

        cards = tv.statuses_to_data(result.get('statuses'))['cards']
    else:
        cards = []
    return render_template('rate.html', cards = cards, uid = uid, count = count)
Esempio n. 7
0
import time
from collections import defaultdict
from snownlp import SnowNLP
import pandas as pd
import echarts_countries_pypkg, echarts_china_provinces_pypkg
from pyecharts import Map

client_key = '3536121960'
client_secret = '29a7cb9342f584e7a2fda64124ec01cf'
redirect_url = 'https://api.weibo.com/oauth2/default.html'
auth = WeiboOauth2(client_key, client_secret, redirect_url)
webbrowser.open(auth.authorize_url)
code = input('the code is\n')
token = auth.auth_access(code)

client = WeiboClient(token['access_token'])
#获取的内容处理:1.删去回复
#2.按地域划分内容
province_list = defaultdict(list)
comment_text_list = []

for i in range(1, 40):
    try:
        result = client.get(suffix='comments/show.json',
                            params={
                                'id': 4401542310862649,
                                'count': 200,
                                'page': 1
                            })
        comments = result['comments']
        if not len(comments):
Esempio n. 8
0
import pandas as pd
import time
import webbrowser  #.net控件
import re  #正则表达式

#获取微博访问权限
client_key = '1682831498'
client_secret = '1d59150536c692bed24d59d46ae2b32d'
redirect_url = 'https://api.weibo.com/oauth2/default.html'  #授权回调页
auth = WeiboOauth2(client_key, client_secret, redirect_url)  #第三方应用请求用户授权
webbrowser.open_new(auth.authorize_url)  #通过net控件自动启动web浏览器访问url
code = input('输入code:')  #获得服务器授权的授权码(用户授权)
token = auth.auth_access(code)  #第三方应用向服务器请求授权
print(token)  #凭借token向资源服务器请求资源
#调用API接口获得数据
client = WeiboClient(token['access_token'])
print(client)

#表头定义
name = ['user_name', 'created_at', 'attitudes_count', 'comments']

#评论内容预处理
comment_text_list = []  #评论内容
user_name = []  #用户ID
created_at = []  #评论时间
attitudes_count = []  #点赞数量

for i in range(1, 50):
    result = client.get(suffix='comments/show.json',
                        params={
                            'id': 4573338503217812,
Esempio n. 9
0
## 3、获得授权
# 获取token 和 token的生命周期
r = client.auth_access(code)
# print(r)
# {'access_token': u'2.0053aLTGSNOMYCc0217260bahxd6uC', 'expires': 1693066525, 'expires_in': 1693066525, 'uid': u'5928072116'}
access_token = r.get("access_token")
# print(access_token)
# 2.0053aLTGSNOMYCc0217260bahxd6uC
expires_in = r.expires_in
# print(expires_in)
# 1693066525

## 4、为以后的API请求设置token
from weibopy import WeiboClient

client = WeiboClient(access_token)

## 5、获取当前登录用户及其所关注(授权)用户的最新微博 statuses/home_timeline
# https://api.weibo.com/2/statuses/home_timeline.json
result = client.get(suffix="statuses/home_timeline.json")
statuses = result.get("statuses")
# print(statuses[0])
length = len(statuses)
print(length)
# 输出了部分信息
for i in range(0, length):
    print(u'昵称:' + statuses[i]['user']['screen_name'])
    print(u'简介:' + statuses[i]['user']['description'])
    print(u'位置:' + statuses[i]['user']['location'])
    print(u'微博:' + statuses[i]['text'])
Esempio n. 10
0
class WeiboRequestTestCase(unittest.TestCase):
    """
    """
    def setUp(self):
        """
        :return:
        """
        self.token = "1qaz3edc"
        self.client = WeiboClient(self.token)

    def test_weibo_request(self):
        """
        :return:
        """

        body = """
        {"next_cursor": 4098746105417334, "hasvisible": false, "uve_blank": -1, "statuses": ["4098748692646689",
        "4098748689403910", "4098748688918202", "4098747640117551", "4098747434341769", "4098747430814353",
        "4098747430145399", "4098747052681634", "4098746357066702", "4098746322855226", "4098746297959121",
        "4098746251989195", "4098746226771596", "4098746205413046", "4098746180805829", "4098746175979920",
         "4098746172045575", "4098746172045403", "4098746160243131", "4098746139219122"], "ad": [],
         "advertises": [], "interval": 0, "previous_cursor": 0, "total_number": 1322}
        """
        httpretty.register_uri(
            httpretty.GET,
            "https://api.weibo.com/2/statuses/friends_timeline/ids.json",
            body=body,
            status=200,
            content_type='text/json')

        self.assertDictEqual(
            self.client.get("statuses/friends_timeline/ids.json"),
            json.loads(body))

    def test_weibo_post(self):
        """
        :return:
        """
        body = """
              {
          "attitudes_count": 0,
          "biz_feature": 0,
          "comments_count": 0,
          "created_at": "Thu Apr 20 23:18:30 +0800 2017",
          "darwin_tags": [],
          "favorited": false,
          "geo": null,
          "gif_ids": null,
          "hasActionTypeCard": 0,
          "hot_weibo_tags": [],
          "id": 4098749565013950,
          "idstr": "4098749565013950",
          "in_reply_to_screen_name": "",
          "in_reply_to_status_id": "",
          "in_reply_to_user_id": "",
          "isLongText": false,
          "is_show_bulletin": 2,
          "mid": "4098749565013950",
          "mlevel": 0,
          "pic_urls": [],
          "positive_recom_flag": 0,
          "reposts_count": 0,
          "source": "<a href='http://open.weibo.com' rel='nofollow'>app</a>",
          "source_allowclick": 0,
          "source_type": 1,
          "text": "haha",
          "textLength": 4,
          "text_tag_tips": [],
          "truncated": false,
          "user": {
            "allow_all_act_msg": false,
            "allow_all_comment": true,
            "avatar_hd": "http://tva4.sinaimg.cn/crop.320.120.960.960.1024/70669a5djw1eanuztfpewj218g0xcn9c.jpg",
            "avatar_large": "http://tva4.sinaimg.cn/crop.320.120.960.960.180/70669a5djw1eanuztfpewj218g0xcn9c.jpg",
            "bi_followers_count": 9,
            "block_app": 0,
            "block_word": 0,
            "city": "2",
            "class": 1,
            "created_at": "Tue Dec 07 21:44:06 +0800 2010",
            "credit_score": 80,
            "description": "",
            "domain": "nooper",
            "favourites_count": 3,
            "follow_me": false,
            "followers_count": 48,
            "following": false,
            "friends_count": 140,
            "gender": "m",
            "geo_enabled": true,
            "id": 1885772381,
            "idstr": "1885772381",
            "insecurity": {
              "sexual_content": false
            },
            "lang": "zh-cn",
            "online_status": 0,
            "pagefriends_count": 0,
            "profile_image_url": "http://tva4.sinaimg.cn/crop.320.120.960.960.50/70669a5djw1eanuztfpewj218g0xcn9c.jpg",
            "profile_url": "nooper",
            "province": "11",
            "ptype": 0,
            "remark": "",
            "screen_name": "nooper",
            "star": 0,
            "statuses_count": 168,
            "urank": 13,
            "url": "",
            "user_ability": 0,
            "verified": false,
            "verified_reason": "",
            "verified_reason_url": "",
            "verified_source": "",
            "verified_source_url": "",
            "verified_trade": "",
            "verified_type": -1,
            "weihao": ""
          },
          "userType": 590081,
          "visible": {
            "list_id": 0,
            "type": 0
          }
        }
        """
        httpretty.register_uri(httpretty.POST,
                               "https://api.weibo.com/2/statuses/update.json",
                               body=body,
                               status=200,
                               content_type='text/json')

        self.assertDictEqual(self.client.post("statuses/update.json"),
                             json.loads(body))

    def test_weibo_api_error(self):
        """
        :return:
        """
        body = """
                {
                        "request": "/statuses/home_timeline.json",
                        "error_code": "20502",
                        "error": "Need you follow uid."
                }
                """
        httpretty.register_uri(
            httpretty.GET,
            "https://api.weibo.com/2/statuses/home_timeline.json",
            body=body,
            status=200,
            content_type='text/json')

        self.assertRaises(WeiboAPIError, self.client.get,
                          "statuses/home_timeline.json")
Esempio n. 11
0
 def setUp(self):
     """
     :return:
     """
     self.token = "1qaz3edc"
     self.client = WeiboClient(self.token)
Esempio n. 12
0
from weibopy import WeiboOauth2, WeiboClient
import webbrowser

client_key = '216******'
client_secret = '544a3********************'
redirect_url = 'https://api.weibo.com/oauth2/default.html'

auth = WeiboOauth2(client_key, client_secret, redirect_url)

webbrowser.open_new(auth.authorize_url)

code = input('输入 code: ')

token = auth.auth_access(code)

print(token)

client = WeiboClient(token['access_token'])

result = client.get(suffix='comments/show.json', params={'id': 4318237070487349, 'count': 200, 'page': 1})

print(result)
Esempio n. 13
0
import time
import re
import jieba
import wordcloud

client_key = ''  # 你的 app key
client_secret = ''  # 你的 app secret
redirect_url = 'https://api.weibo.com/oauth2/default.html'
auth = WeiboOauth2(client_key, client_secret, redirect_url)
# 获取认证 code
webbrowser.open_new(auth.authorize_url)
code = input('输入 code:')
# 使用 code 获取 token
token = auth.auth_access(code)
# token 是刚刚获得的 token,可以一直使用
client = WeiboClient(token['access_token'])

comment_text_list = []  # 保存所有评论正文

# 共获取 10 页 * 每页最多 200 条评论
for i in range(1, 11):
    result = client.get('comments/show.json',
                        params={
                            'id': 4448468472919660,
                            'count': 200,
                        })

    comments = result['comments']
    if not len(comments):
        break
Esempio n. 14
0
import webbrowser

client_key = '262607354'                            # 你的 app key
client_secret = '5345921237fa4ebe8d555a471f5a8da1'  # 你的 app secret
redirect_url = 'https://api.weibo.com/oauth2/default.html'

auth = WeiboOauth2(client_key, client_secret, redirect_url)
# 获取认证 code
webbrowser.open_new(auth.authorize_url)

# 在打开的浏览器中完成操作
# 最终会跳转到一个显示 「微博 OAuth2.0」字样的页面
# 从这个页面的 URL 中复制 code= 后的字符串
# URL 类似这样 https://api.weibo.com/oauth2/default.html?code=9c88ff5051d273522700a6b0261f21e6

code = input('输入 code:')

# 使用 code 获取 token
token = auth.auth_access(code)

print(token)

# token 是刚刚获得的 token,可以一直使用
client = WeiboClient(token['access_token'])

# suffix 指定 API 的名称,parmas 是参数,在文档中有详细描述
result = client.get(suffix='comments/show.json',
                    params={'id': 4416407817336332, 'count': 200, 'page': 10})

print(result)
Esempio n. 15
0
client_key = '3108629810'
client_secret = '7a3024d73e832f4309b57e35fb35748f'
redirect_url = 'https://api.weibo.com/oauth2/default.html'

auth = WeiboOauth2(client_key,client_secret,redirect_url)

webbrowser.open_new(auth.authorize_url)

code = input('输入:')

token = auth.auth_access(code)

print(token)

client = WeiboClient(token['access_token'])

'''result = client.get(suffix='comments/show.json',params={'id':4322140368509204,'count':200,'page':1})'''

province_list = defaultdict(list)
comment_text_list = []
for i in range (1,5):
    result = client.get(suffix='comment/show.json',params={'id':4322140368509204,'count':200,'page':i})
    comments = result['comments']
    if not len(comments):
        break

    for comment in comments:
        text = re.sub('回复.*?:', '', str(comment['text']))
        province_list[province].append(text)
        comment_text_list.append(text)
Esempio n. 16
0
from weibopy import WeiboOauth2, WeiboClient
from collections import defaultdict
import time, re

client = WeiboClient("2.00smBtiFZt3nrCbd3c406d87mTFJMB")

# suffix 指定 API 的名称,parmas 是参数,在文档中有详细描述

province_list = defaultdict(list)  # 保存按省划分的评论正文
comment_text_list = []  # 保存所有评论正文
provinces = {}

results = client.get(suffix='common/get_province.json',
                     params={'country': '001'})
for prov in results:
    for code, name in prov.items():
        provinces[code] = name
print(provinces)

# 获取「自杀式单身」评论列表
# 共获取 10 页 * 每页最多 200 条评论
for i in range(1, 11):
    result = client.get(suffix='comments/show.json',
                        params={
                            'id': 4322140368509204,
                            'count': 200,
                            'page': i
                        })

    comments = result['comments']
    if not len(comments):
Esempio n. 17
0
 def setUp(self):
     """
     :return:
     """
     self.token = "2.004jcLBHVga43C200e107f4c00TUIZ"
     self.client = WeiboClient(self.token)