小编Fil*_*ipa的帖子

使用 Tweepy 时处理连接错误

希望你一切都好。

我正在尝试使用 tweepy 库长时间连续提取推文。为此,我有一个无限循环运行的 python 脚本。唯一的问题是,每次连接失败时,由于任何可能的原因,我的脚本都会崩溃,我将不得不重新启动它。所以我想让它特别针对连接错误,为此我使用 try... except 条件,但它似乎不起作用。我已经尝试了网上找到的所有内容,但没有任何效果,有人可以帮助我吗?

这是我的代码:

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

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

city = 'LX'
country = 'PT'
coord = '38.736946,-9.142685'
radius = '25km'

while True:
    today = datetime.now()

    if len(str(today.month)) == 1:
        month = str(0) + str(today.month)
    else:
        month = str(today.month)    
    n=10
    tweets=tweepy.Cursor(api.search_tweets,q="",geocode=coord+','+radius,tweet_mode="extended").items(n)
 
    fname = f'{country}_{city}_{today.day}{month}{str(today.year)[2:]}.json'

    with open(fname, 'a') as outfile:
        for tweet in tweets:
            try: 
                outfile.write(json.dumps(tweet._json))
                outfile.write('\n') …
Run Code Online (Sandbox Code Playgroud)

python tweepy twitterapi-python

1
推荐指数
1
解决办法
198
查看次数

标签 统计

python ×1

tweepy ×1

twitterapi-python ×1