简体   繁体   中英

Python: Using if and else statements to loop

I have written a scrip that requests a URL, if the response is is 'CAPCHA_NOT_READY' then the script should sleep for 5 seconds and then request the URL again. If the response starts with 'OK' then the scrip should continue.

I am not sure at how I set up this loop. Thanks, Piers.

r = requests.get(url)
print("Sending Captcha To 2captcha")
print("Captcha ID = "+(r.text))

time.sleep(5)

url2 = "http://2captcha.com/res.php?key="+api+"action=get&id="+(r.text)[3:]
print(url2)
r = requests.get(url2)
print(r.text)

if r.text == "CAPCHA_NOT_READY":
    time.sleep(5)
    r = requests.get(url2)
    print(r.text) 

So far what I understand you wanted to get the captcha from url and send it to url2 and request url2 in every 5 secs until is succeeded.

r = requests.get(url)
print("Sending Captcha To 2captcha")
print("Captcha ID = "+(r.text))
CAPTCHA_ID = r.text
time.sleep(5)

CAPTCHA_TEXT = True
while CAPTCHA_TEXT:
    url2 = "http://2captcha.com/res.php?key="+api+"action=get&id="+(CAPTCHA_ID)[3:]
    r = requests.get(url2)
    if r.text == 'CAPCHA_NOT_READY':
        time.sleep(5)
    if r.text == 'OK':
        CAPTCHA_TEXT = False

This would be my approach:

r = requests.get(url)

url = ("http://2captcha.com/res.php?"
       "key={api_key}&action=get&id={req_id}"
       .format(
           api_key=api,
           req_id=r.text[3:],
       ))

is_capcha_ready = False

while not is_capcha_ready:

    if requests.get(url).text == "CAPCHA_NOT_READY":
        time.sleep(5)
    else:
        is_capcha_ready = True

If requests comes from the requests library, you can also pass the querystring as the data keyword argument.

http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM