当前位置: 代码迷 >> python >> 无法使用Tweepy下载搜索到的推文
  详细解决方案

无法使用Tweepy下载搜索到的推文

热度:93   发布时间:2023-06-13 17:14:44.0

我以前使用过以下脚本,但现在无法使用。 我没有在终端中打印任何推文(如第38行中的代码所示),也没有在我的csv中存储任何推文。 我没有什么问题。

import tweepy
import csv
import time

access_token = "xxxxxxxxxx"
access_token_secret = "xxxxxxxxxx"
consumer_key = "xxxxxxxxxx"
consumer_secret = "xxxxxxxxxx"


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

print "Starting search..."

#
# Open/Create a file to append data
csvFile = open('somesearch.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)


searchTerms = ["#Xfactor", "#Yfactor"]


tweets= tweepy.Cursor(api.search,q=[searchTerms], \
                      since="2015-10-18",
                      until="2015-10-23",
                      include_entities=True).items(999999999)

#csvWriter.writerow([tweet.created_at, tweet.id_str, tweet.screen_name, tweet.user_id, tweet.coordinates, tweet.place, tweet.text.encode('utf-8'), tweet.retweet_count, tweet.favorite_count])
#tweet.in_reply_to_user_id_str, tweet.in_reply_to_screen_name, tweet.in_reply_to_status_id_str, tweet.retweeted, tweet.truncated, tweet.source

while True:
    try:
        for tweet in tweets:
            print tweet.created_at, tweet.text.encode('utf-8')
            csvWriter.writerow([tweet.created_at, tweet.id_str, tweet.author.name.encode('utf-8'), tweet.author.screen_name.encode('utf-8'),
                                tweet.user.location.encode('utf-8'), tweet.coordinates, tweet.text.encode('utf-8'), tweet.retweet_count, tweet.favorite_count])
    except tweepy.TweepError:
        time.sleep(60 * 15)
        continue
    except StopIteration:
        break

print "Done!"

问题出在这一行:

tweets= tweepy.Cursor(api.search,q=[searchTerms],

您所做的就是创建一个包含列表的列表。 看下面的代码:

searchTerms = ["#Xfactor", "#Yfactor"]
q=[searchTerms]

print(searchTerms)
>>> ['#Xfactor', '#Yfactor']
print(type(q))
>>> [['#Xfactor', '#Yfactor']]

您要搜索的不是searchTerms ,而是要搜索的列表。

因此,现在您感兴趣的tweet 必须包含文字['#Xfactor', '#Yfactor'] 要解决该问题,请将q更改为:

tweets= tweepy.Cursor(api.search,q=searchTerms,