简体   繁体   English

退出python函数错误

[英]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: 当出现这两个错误之一时,说明存在一个错误,例如以下示例:

在此处输入图片说明

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. 如您所见,首先出现错误的验证码类型无效(nieznany typ captcha),然后该函数再次运行并成功创建了帐户(ZAREJESTROWANO),该函数应停止运行。 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). 但是,正如您在映像上看到的那样(从控制台),它再次运行(BŁĘDNECAPTCHA)。

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. 我试过清除'text'变量,甚至添加'koniec'变量,但它不能解决问题。 Any ideas? 有任何想法吗?

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) 如果1)您不希望函数完全复位,2)您不希望求值返回到调用该函数的位置(例如在except块中create_account() ,则不应再次调用create_account()

Also, koniec = 'nie' will make that always be set before the if statements, so checking it against anything else doesn't make sense. 另外, koniec = 'nie'将使该值始终在if语句之前设置,因此将其与其他任何内容进行检查都没有意义。

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 

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. 看起来在代码中途经过try / except块的try / except块中对create_account()的调用似乎是问题所在,它将递归并返回到周围的代码,然后继续执行if / else块。 (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. 顺便说一句,此代码的整体结构相当混乱,我怀疑这是由于您没有使用for循环或while循环而不是递归而引起的。 Also, you should avoid global variables as much as possible, since they will also confuse the control flow of the program, especially with recursion. 另外,您应尽可能避免使用global变量,因为它们也会使程序的控制流程混乱,尤其是在递归时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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