Я пытаюсь очистить Twitter с помощью библиотеки GetOldTweets. Я включил библиотеку и попытался смягчить слишком много твитов, просматривая их день за днем, а также ограничивая каждый захват данных до 1000 твитов.
До нескольких дней go все работало нормально. Если он обнаружил ошибку 429, он просто перехватил ошибку, начал «спать», а затем сделал новый запрос после истечения срока «сна». В последние несколько дней он перестал перехватывать HTTPError, и программа мгновенно завершается сбоем. Я ломаю голову над тем, почему он только недавно перестал работать, а также над тем, как это исправить, так как не вижу, что еще делать.
An error occured during an HTTP request: HTTP Error 429: Too Many Requests
Try to open in browser: https://twitter.com/search?q=%27premier%20league%27%20-filter%3Aretweets%20since%3A2020-01-01%20until%3A2020-01-02&src=typd
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/GetOldTweets3/manager/TweetManager.py in getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy, useragent, debug)
342 try:
--> 343 response = opener.open(url)
344 jsonResponse = response.read()
~/anaconda3/lib/python3.6/urllib/request.py in open(self, fullurl, data, timeout)
531 meth = getattr(processor, meth_name)
--> 532 response = meth(req, response)
533
~/anaconda3/lib/python3.6/urllib/request.py in http_response(self, request, response)
641 response = self.parent.error(
--> 642 'http', request, response, code, msg, hdrs)
643
~/anaconda3/lib/python3.6/urllib/request.py in error(self, proto, *args)
569 args = (dict, 'default', 'http_error_default') + orig_args
--> 570 return self._call_chain(*args)
571
~/anaconda3/lib/python3.6/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
503 func = getattr(handler, meth_name)
--> 504 result = func(*args)
505 if result is not None:
~/anaconda3/lib/python3.6/urllib/request.py in http_error_default(self, req, fp, code, msg, hdrs)
649 def http_error_default(self, req, fp, code, msg, hdrs):
--> 650 raise HTTPError(req.full_url, code, msg, hdrs, fp)
651
HTTPError: HTTP Error 429: Too Many Requests
During handling of the above exception, another exception occurred:
SystemExit Traceback (most recent call last)
<timed exec> in <module>
~/anaconda3/lib/python3.6/site-packages/GetOldTweets3/manager/TweetManager.py in getTweets(tweetCriteria, receiveBuffer, bufferLength, proxy, debug)
63 active = True
64 while active:
---> 65 json = TweetManager.getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy, user_agent, debug=debug)
66 if len(json['items_html'].strip()) == 0:
67 break
~/anaconda3/lib/python3.6/site-packages/GetOldTweets3/manager/TweetManager.py in getJsonResponse(tweetCriteria, refreshCursor, cookieJar, proxy, useragent, debug)
346 print("An error occured during an HTTP request:", str(e))
347 print("Try to open in browser: https://twitter.com/search?q=%s&src=typd" % urllib.parse.quote(urlGetData))
--> 348 sys.exit()
349
350 try:
SystemExit:
Мой код ниже:
from urllib import error
import GetOldTweets3 as got
import time
tweets_array = []
for date in dates:
#Dates is a list of tuples i.e. [(2020-01-01,2020-01-02),(2020-01-02,2020-01-03),...]
since_id = ""
error_count = 0
tweet_query = f'\'premier league\' -filter:retweets'
flag = True
since_date = date[0]
to_date = date[1]
while flag:
try:
tweetCriteria = got.manager.TweetCriteria().setQuerySearch(tweet_query).setMaxTweets(1000).setUntil(to_date).setSince(since_date)
%time tweets = got.manager.TweetManager.getTweets(tweetCriteria)
#Check if the last available tweet id is the same as the previous last, if so it has reached the limit for that day
if tweets[-1].id == since_id:
print("No further tweets for this day")
flag = False
else:
for x in tweets:
tweets_array.append(x)
since_id = tweets[-1].id
tweet_query = f'\'premier league\' -filter:retweets max_id:{since_id}'
except error.HTTPError as e:
print('HTTP Error 429: ',e)
time.sleep(60*5)