【问题标题】:unexpected error argument wait limit on a tweepy python scripttweepy python脚本上的意外错误参数等待限制
【发布时间】:2019-02-26 07:53:51
【问题描述】:

几个月前我使用了这个 twitter python 脚本,它正在工作。我不知道我可能不小心更改了什么,但我现在收到一条错误消息:

我明白了

第 32 行,在 api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) TypeError: init() got an 意外的关键字参数“wait_on_rate_limit”

运行此脚本时出错。

有人能帮我理解为什么吗?非常感谢!

#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4


import tweepy
from tweepy import OAuthHandler
import getopt
import json
import time
import os
import sys

# Vecteurs d'accreditation a renseigner
# apres creation dans le gestionnaire d'applications Twitter 
# cf : https://apps.twitter.com/
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""

# Constantes
maxTweets = 10000000   # Nombre de tweet max a recuperer
tw_block_size = 100    # Nombre de Tweet par requete
sinceId = None         # Recuperation des tweets du plus recent au plus ancien

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

def usage():
    """
    Display usage
    """
    sys.stderr.write( "Usage: collect.py -s <hashtag> | --search=<hashtag>\n"+
                      "                 [-o <output-dir> | --output-dir=<output-dir>]\n"+
                      "                 [-m <max-id> | --maxid=<max-id>]\n")

def main(argv):
    """
    Collecte des tweets associe a un hashtag.
    """
    tweetCount = 0
    search_query = None
    max_id = -1L
    output_dir = "."

    try:
        opts, args = getopt.getopt(argv, "ho:s:m:", ["help","output-dir=","search=","maxid="])
    except getopt.GetoptError:
        usage()
        sys.exit(1)

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        if o in ("-s", "--search" ):
            search_query = a
        if o in ("-o", "--output-dir" ):
            output_dir = a
        if o in ("-m", "--maxid" ):
            max_id = long(a)

    if not search_query:
        usage()
        sys.exit(2)

    print("Parametres de la collecte :")
    print(" - Hashtag    : {0}".format(search_query))
    print(" - Repertoire : {0}".format(output_dir))
    print(" - Max ID     : {0}".format(max_id))
    print("")

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    while tweetCount < maxTweets:
         try:
             if (max_id <= 0):
                 if (not sinceId):
                     new_tweets = api.search(q=search_query, count=tw_block_size)
                 else:
                     new_tweets = api.search(q=search_query, count=tw_block_size, since_id=sinceId)

             else:
                 if (not sinceId):
                     new_tweets = api.search(q=search_query, count=tw_block_size, max_id=str(max_id - 1))
                 else:
                     new_tweets = api.search(q=search_query, count=tw_block_size, max_id=str(max_id - 1), since_id=sinceId)

             if not new_tweets:
                 print("Collecte terminee.")
                 break
             for tweet in new_tweets:
                 day = tweet.created_at.strftime('%Y-%m-%d')
                 with open( "%s/%s_tweets.json" % (output_dir, day), 'a') as f:
                     f.write(json.dumps(tweet._json))
                     f.write('\n')
             tweetCount += len(new_tweets)
             print("{0} tweets téléchargés".format(tweetCount))
             max_id = new_tweets[-1].id
         except tweepy.TweepError as e:
             print("Une erreur est intervenue. Pour poursuivre le processus de collecte, relancer la commande suivante :")
             print("python collect.py -s \"{0}\" -o \"{1}\" -m \"{2}\"".format(search_query, output_dir, max_id))
             print("")
             print("Error : " + str(e))
             break

if __name__ == "__main__":
    main(sys.argv[1:])

【问题讨论】:

    标签: python-2.7 tweepy


    【解决方案1】:

    此脚本适用于我的 Python 2.7.15 和 Tweepy 3.7.0,请确保您使用的是最新版本的 Tweepy。您的错误可能与旧版本的 Tweepy 有关,如下所述:TypeError: __init__() got an unexpected keyword argument 'wait_on_rate_limit'

    要检查您的 Tweepy 版本:pip show tweepy,要升级:pip install tweepy --upgrade

    请注意,标准搜索 API 不会返回超过 10 天的状态。官方 Twitter API 文档提到了这一点:“请记住,搜索索引有 7 天的限制”,尽管我遇到的实际限制是 10 天。要超越这个限制,您可以使用像 https://github.com/jonbakerfish/TweetScraper 这样的网络爬虫,它根本不使用官方 API。

    【讨论】:

    • 赞美主!我安装了一个 tweepy-utils 包,它改变了 tweepy 的版本。升级......它再次工作。非常感谢,再次感谢 Scrapper GitHub 项目!
    • 不客气。如果我的回答对您有帮助,您介意接受吗?这就是它的完成方式:meta.stackexchange.com/questions/5234/… 谢谢。
    猜你喜欢
    • 2022-01-04
    • 2023-03-15
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多