【问题标题】:Fetch metadata for tweet ids using tweepy is not working anymore使用 tweepy 获取推文 ID 的元数据不再有效
【发布时间】:2021-08-02 17:03:53
【问题描述】:

我使用 tweepy 库(用于 twitter api-v1.1)来获取一些元数据(例如,推文文本、#retweets、用户 ID 等)以获取推文 ID 列表。这是我的代码:

consumer_key = 'xxxxxxxxxxxx'
consumer_key_secret = 'xxxxxxxxxxxx'
access_token = 'xxxxxxxxxxxxxxxxxx'
access_token_secret = 'xxxxxxxxxxxxxxxxxx'

auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

def createTrainingSet(corpusFile, tweetContent):
    import csv
    import time
    import json

    counter = 0
    corpus = []

    with open(corpusFile, 'r') as csvfile:
        lineReader = csv.reader(csvfile, delimiter=',')
        for row in lineReader:
            corpus.append({"tweet_id": row[0], "unreliable": row[1], "conspiracy": row[2],\
                           "clickbait": row[3], "political/biased": row[4], "date": row[5]})

    sleepTime = 2
    trainingDataSet = []  
    
    for tweet in corpus:
        try:
            tweetFetched = api.get_status(tweet["tweet_id"])
            print("Tweet fetched" + tweetFetched.text)
            print("followers_count: "+ str(tweetFetched.user.followers_count))
            print("friends_count: " + str(tweetFetched.user.friends_count))
            
            tweet["text"] = tweetFetched.text
            tweet["retweet_count"] = tweetFetched.retweet_count
            tweet["favorite_count"] = tweetFetched.favorite_count
            tweet["created_at"] = tweetFetched.created_at   
            tweet["user_id"] = tweetFetched.user.id_str
            tweet["user_created_at"] = tweetFetched.user.created_at              
            
            trainingDataSet.append(tweet)
            time.sleep(sleepTime)

        except:
            print("Inside the exception - no:2")
            continue

# This is corpus dataset
corpusFile = "sample.csv"
# This is my target file
tweetContent = "tweetContent.csv"
# Call the method
resultFile = createTrainingSet(corpusFile, tweetContent)

我不知道为什么这段代码不再起作用(它最后一次起作用是几个月前的一次)。但是,当我现在运行它时,它会返回 "Inside the exception - no:2"。这是为什么呢?

【问题讨论】:

  • 您能否提出异常并添加它所说的内容,而不是打印和继续?
  • 如果没有实际的异常/回溯,就不可能确定问题所在。
  • 感谢@NelsonGon 的提示。我现在会发布答案:)
  • @Harmon758 感谢您的提示。我现在会发布答案:)

标签: python metadata tweepy twitterapi-python


【解决方案1】:

这是帮助我找到错误的两行代码:

except tweepy.TweepError as e:
        print ('the error code:', e.args[0][0]['code'])
        print ('the error message:', e.args[0][0]['message'])  

另外,感谢Jeyekomon's answer in this post,我发现e.message[0]['code'] 不再工作了:

以前使用 e.message[0]['code'] 访问的错误代码不再有效。 message 属性在 Python 2.6 中已被弃用,并在 Python 3.0 中被删除。目前你得到一个错误'TweepError' object has no attribute 'message'

此外,TweepError 异常类中似乎还有一些其他有用的属性(api_codereasonresponse)不在文档中。

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2015-04-27
    相关资源
    最近更新 更多