设置函数的到期时间以进行重试

时间:2018-02-12 20:29:31

标签: python captcha

我正在收集验证码,并且验证码响应只有2分钟。我试图找出如何设置"过期,再次获取"功能

def captchaToken():
    global captoken
    s = requests.Session()
    # here we post site key to 2captcha to get captcha ID (and we parse it here too)
    captcha_id = s.post("http://2captcha.com/in.php?key={}&method=userrecaptcha&googlekey={}&pageurl={}".format(APItoken, sitekey, url)).text.split('|')[1]
    #time.sleep(5)
    print("Waiting for captcha...")
    # then we parse gresponse from 2captcha response
    recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(APItoken, captcha_id)).text
    print("Solving captcha...")
    while 'CAPCHA_NOT_READY' in recaptcha_answer:
        print("Waiting for a response . . .")
        time.sleep(2.5)
        recaptcha_answer = s.get("http://2captcha.com/res.php?key={}&action=get&id={}".format(APItoken, captcha_id)).text
    recaptcha_answer = recaptcha_answer.split('|')[1]
    captoken = recaptcha_answer
    print(Fore.MAGENTA + "Captcha Response: "+recaptcha_answer)

1 个答案:

答案 0 :(得分:0)

我建议:

while 1:
   captcha = get_captcha()
   request = post_captcha(captcha)
   start = time.time()
   while 1:
      response = poll_for_result(request)
      if start + 120 < time.time():
         time_is_up()
         break
      if response:
         return deal_with_response(response)