1

我正在使用 Twint(一个 Twitter 抓取工具),但不知何故有一个我无法解决的问题。我想知道是否有一种方法可以在发生错误时等待1分钟并重新执行?我的代码是这样的:

import twint

geos = ["40.74566208501717, -73.99137569478954", "35.68802408270403, 139.76489869554837", "31.22521968438549, 121.51655148017774"]
    
for geo in geos:
    print(str(geo)+','+'10km')
    c = twint.Config()
    c.Limit = 20
    c.Geo = str(geo)+','+'10km'
    twint.run.Search(c)

有时,twint.run.Search(c)无法正常运行。那么,一旦出现错误,有没有办法只再次执行此循环而不重新执行整个循环?

有人会帮助我吗?任何想法都会非常有帮助。非常感谢!

4

2 回答 2

2

如果你想简单地假装错误没有发生,你可以这样做:

try:
    twint.run.Search(c)
except WhateverExceptionType:
    pass

(替换WhateverExceptionType为您看到的实际错误类型)

如果出现错误时您想让整个程序在继续循环之前等待一分钟,请将其放入except

import time

...

    try:
        twint.run.Search(c)
    except WhateverExceptionType:
        time.sleep(60)

If you want it to re-execute that specific search after waiting (rather than continuing with the next loop iteration), put that in the except. Note that if code within an except raises, then it will raise out of the except and stop your program.

    try:
        twint.run.Search(c)
    except WhateverExceptionType:
        time.sleep(60)
        twint.run.Search(c)
于 2021-12-16T16:28:51.040 回答
0

You could do something like this to try the search again after 60 sec and with say maximum 10 retries:

import time

for geo in geos:
    print(str(geo)+','+'10km')
    c = twint.Config()
    c.Limit = 20
    c.Geo = str(geo)+','+'10km'

    success=False
    retries = 0
    while not success and retries <= 10:
        try:
            twint.run.Search(c)
            success=True
        except twint.token.RefreshTokenException:
            time.sleep(60)
            retries += 1
        except: # <- catches all other exceptions
            retries = 11  # <- e.g. stop trying if another exception was raised
于 2021-12-16T16:30:19.770 回答