Twitter时间线迭代,以获得我的所有推文与for循环

时间:2015-08-06 09:02:36

标签: python twitter iteration timeline

使用这个脚本我试图用twitter api迭代我的时间线。 我在“for”循环中使用时间延迟将所有推文都放在这样的对象列表中:

x = [<twitter.status.Status at 0x7fb23b7c5090>, <twitter.status.Status at 0x7fb5fdb7c5090>,<twitter.status.Status at 0x7fbs4b7c5090>,<twitter.status.Status at 0x7f255b7c5090>, ...]

#Setting the connection:
api = twitter.Api(consumer_key= cons_key,
                  consumer_secret = cons_secret,
                  access_token_key = accs_token,
                  access_token_secret = accs_token_secret)

#Getting the latest id and put it on a list called "lis"

x = api.GetUserTimeline(screen_name = "My_Username", count = 1, include_rts = True)
lis=[x[0].id]

#Creating a list to append my twitter status objects.
tweet_info = []

## Iterate through all tweets, say for example 4 times
for i in range(0, 4): 
## tweet extract method with the last list item as the max_id

    user_timeline = api.GetUserTimeline(screen_name="My_Username",
    count=3, include_rts = True, max_id=lis[-1])

    time.sleep(2) ## 2 seconds rest between api calls

    for tweet in range(len(user_timeline)):
    x = user_timeline[tweet]
        tweet_info.append(x)
        lis.append(tweet['id']) #appending the id's in order to my list in order to extract the last one for the next time it iterates.

当我运行我的代码时,我收到此错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-103-11f235fc3b3a> in <module>()
      7         x = user_timeline[tweet]
      8         tweet_info.append(x)
----> 9         lis.append(tweet['id'])

TypeError: 'int' object has no attribute '__getitem__'

我做错了什么以及如何解决?

1 个答案:

答案 0 :(得分:0)

这是因为推文是integer

您的代码:

for tweet in range(len(user_timeline)):
    x = user_timeline[tweet]
    tweet_info.append(x)
    lis.append(tweet['id'])

您在内部执行此操作:

1["id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

那是:

 for i in range(len(a)):
    print i
    print i["id"]

 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'