Daniel Koczuła
Daniel Koczuła

Reputation: 1034

Exit python function error

I've got a function to create accout on some website. It makes it automatically with solving captcha.

Here's my function:

def create_account():
    global login
    global password
    global email

    print('# REJESTROWANIE NOWEGO KONTA')

    s=requests.Session()
    headers = {
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'en-US,en;q=0.8',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
    }
    s.headers.update(headers)
    r=s.get(REGISTER_URL)
    soup=BeautifulSoup(r.content, "html.parser")
    captcha_img=soup.find("img",{"alt":"captcha"})['src']

    nazwa = basename(captcha_img)
    capublic = str(os.path.splitext(nazwa)[0])

    with open('/root/environments/captcha_img/'+nazwa,"wb") as f:
        f.write(requests.get('https://www.mywebsite.net/'+captcha_img).content)

    captcha_text = ''

    try:
        captcha_text = captcha('captcha_img/'+nazwa)
        filelist = [ f for f in os.listdir('/root/environments/captcha_img/') if f.endswith(".png") ]
        for f in filelist:
            os.remove(os.path.join('/root/environments/captcha_img/', f))
    except:
        print('> nieznany typ captcha')
        print('> ponawiam')
        text = ''
        create_account()

    data={
        "jscheck": '1',
        "login": login,
        "pass": password,
        "pass2":password,
        "email": email,
        "cacheck":captcha_text,
        "capublic":capublic,
        'button_submit': 'Sign+Up+(Free)',
    }

    r=s.post(REGISTER_URL,headers=headers,data=data)
    text = str(r.content)

    koniec = 'nie'


    if "Your registration was successful" in text:
        print('# ZAREJESTROWANO')
        print('> login: '+login+', hasło: '+password+', email: '+email)
        text = ''
        koniec = 'tak'
        return
    elif "The supplied Captcha is wrong." in text and koniec != 'tak':
        print('# BŁĘDNE CAPTCHA')
        print('> ponawiam')
        text = ''
        create_account()
    elif "Please fill out both Passwordfields." in text and koniec != 'tak':
        print('# NIE WPISANO HASŁA')
        print('> ponawiam')
        text = ''
        create_account()
    elif "The supplied Passwords do not match." in text and koniec != 'tak':
        print('# HASŁA NIE SĄ TAKIE SAME')
        print('> ponawiam')
        text = ''
        create_account()
    elif "Please enter your Username." in text and koniec != 'tak':
        print('# NIE WPISANO LOGINU')
        print('> ponawiam')
        text = ''
        create_account()
    elif "The Username is already in use." in text and koniec != 'tak':
        print('# LOGIN ZAJĘTY')
        print('> generuję nowy login')
        login = get_uname(5, 10, False)
        print('> ponawiam')
        text = ''
        create_account()
    elif "The supplied E-Mail is already in use." in text and koniec != 'tak':
        print('# ADRES EMAIL ZAJĘTY')
        print('> pobieram nowy adres e-mail')
        email = get_email()
        print('> ponawiam')
        text = ''
        create_account()
    else:
        print('# INNY NIEZNANY BŁĄD')
        print('> generuję nowe dane logowania')
        login = get_uname(5, 10, False)
        password = password = get_password(8)
        email = get_email()
        print('> ponawiam')
        text = ''
        create_account()

Sometimes there is an error with solving captcha. There are two errors: when the captcha is wrong or there is unknown captcha type. In both cases I'm running my function again.

When one of this two error appears there is a bug, like in this example:

enter image description here

As You can see, first there was an error Invalid captcha type (nieznany typ captcha) then the function runs again and succesfully created account (ZAREJESTROWANO) and the function should stop. In my code:

if "Your registration was successful" in text:
            print('# ZAREJESTROWANO')
            print('> login: '+login+', hasło: '+password+', email: '+email)
            text = ''
            koniec = 'tak'
            return

But as You can see on the image (from console) it runs again (BŁĘDNE CAPTCHA).

When there is no error captcha and account is created succesfully everything is ok and the function stop.

I've tried clearing 'text' variable and even add 'koniec' variable but it doesnt solve the problem. Any ideas?

Upvotes: 0

Views: 40

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 192043

You should not call create_account() again if 1) you don't want the function to be entirely reset, 2) you don't want evaluation to return back to the point at which you called the function (such as in the except block)

Also, koniec = 'nie' will make that always be set before the if statements, so checking it against anything else doesn't make sense.

Instead, change your code to follow this pattern

def create_account():
    registered = False 

    while not registered:
        # do work
        try:
            captcha_text = captcha('captcha_img/'+nazwa)
        except:
            continue  # repeat the loop 

        if "Your registration was successful" in text:
            registered = True 
            return 
        elif "The supplied Captcha is wrong." in text:
            # just let the while loop repeat the function on its own
            continue # or call continue 

Upvotes: 1

Philip Adler
Philip Adler

Reputation: 2206

It looks like the call to create_account() in the try/except block about half-way through your code is the problem, that will recurse, return to the surrounding code, which will then go on to execute the if/else block again. (An order of events which would explain your output).

As an aside, the overall structure of this code is quite confusing, and I suspect that this arises from the fact that you have not used a for loop or a while loop instead of recursion. Also, you should avoid global variables as much as possible, since they will also confuse the control flow of the program, especially with recursion.

Upvotes: 1

Related Questions