13

我正在使用 tweepy 编写一个 twitter 程序。当我运行此代码时,它会为它们打印 Python ... 值,例如

<tweepy.models.Status object at 0x95ff8cc>

这不好。我如何获得实际的推文?

import tweepy, tweepy.api
key = XXXXX
sec = XXXXX

tok  = XXXXX
tsec = XXXXX

auth = tweepy.OAuthHandler(key, sec)
auth.set_access_token(tok, tsec)
api = tweepy.API(auth)

pub = api.home_timeline()
for i in pub:
        print str(i)
4

5 回答 5

24

通常,您可以使用dir()Python 中的内置函数来检查对象。

看起来 Tweepy 文档在这里非常缺乏,但我想状态对象反映了 Twitter 的 REST 状态格式的结构,参见(例如)https://dev.twitter.com/docs/api/1/get/状态/home_timeline

所以——试试

print dir(status)

查看状态对象中的内容

或者只是,说,

print status.text
print status.user.screen_name
于 2011-10-10T14:47:49.143 回答
3

查看可用于检查返回对象的getstate () get 方法

for i in pub:
    print i.__getstate__()
于 2011-11-29T11:32:16.980 回答
1

api.home_timeline()方法返回与前 20 条推文相对应的 20 个 tweepy.models.Status 对象的列表。也就是说,每条推文都被视为状态类的一个对象。每个 Status 对象都有许多属性,例如 id、text、user、place、created_at 等。

以下代码将打印推文 ID 和文本:

tweets = api.home_timeline()
for tweet in tweets:
  print tweet.id, " : ", tweet.text
于 2016-02-29T14:04:16.183 回答
1

从实际的推文中,如果你想要特定的推文,你必须有一个推文 ID,并使用

tweets = self.api.statuses_lookup(tweetIDs)
for tweet in tweets:
  #tweet obtained
  print(str(tweet['id'])+str(tweet['text']))

或者如果你想要一般的推文使用 twitter 流 api

class StdOutListener(StreamListener):
def __init__(self, outputDatabaseName, collectionName):
    try:
        print("Connecting to database")
        conn=pymongo.MongoClient()
        outputDB = conn[outputDatabaseName]
        self.collection = outputDB[collectionName]
        self.counter = 0
    except pymongo.errors.ConnectionFailure as e:
        print ("Could not connect to MongoDB:")
def on_data(self,data): 
    datajson=json.loads(data)
    if "lang" in datajson and datajson["lang"] == "en" and "text" in datajson:
        self.collection.insert(datajson)

        text=datajson["text"].encode("utf-8") #The text of the tweet
        self.counter += 1
        print(str(self.counter) + " " +str(text))

def on_error(self, status):
    print("ERROR")
    print(status)
def on_connect(self):
    print("You're connected to the streaming server.
l=StdOutListener(dbname,cname)
    auth=OAuthHandler(Auth.consumer_key,Auth.consumer_secret)
    auth.set_access_token(Auth.access_token,Auth.access_token_secret)
    stream=Stream(auth,l)


    stream.filter(track=stopWords)

创建一个继承自 StreamListener 覆盖函数 on_data 的 Stdoutlistener 类,并以 json 格式返回推文,每次获取推文时运行此函数

于 2016-11-03T16:00:54.600 回答
0

在 tweepy Status 实例上,您可以访问该_json属性,该属性返回一个表示原始Tweet 内容的字典。

例如:

type(status)
# tweepy.models.Status

type(status._json)
# dict

status._json.keys()
# dict_keys(['favorite_count', 'contributors', 'id', 'user', ...])
于 2017-01-17T13:41:45.747 回答