退出python函数错误

时间:2018-01-20 15:05:21

标签: python

我有一个功能可以在某些网站上创建accout。它可以自动解决验证码。

这是我的功能:

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()

有时解决验证码会出错。有两个错误:验证码错误或验证码类型未知时。在这两种情况下,我都在重新运行我的功能。

当出现这两个错误之一时,就会出现错误,例如:

enter image description here

正如您所看到的,首先出现错误无效验证码类型(nieznany typ captcha)然后该函数再次运行并成功创建帐户(ZAREJESTROWANO)并且该函数应该停止。在我的代码中:

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

但是正如你可以在图像上看到的那样(来自控制台)它再次运行(BŁĘDNACAPTCHA)。

当没有错误验证码并且成功创建帐户时,一切正常并且函数停止。

我已经尝试清除'text'变量,甚至添加'koniec'变量,但它没有解决问题。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果您不希望该功能完全重置,则不应再次调用create_account() 2)您不希望评估返回到您调用该函数的位置(例如如在除了块)

此外,koniec = 'nie'将始终在if语句之前设置,因此检查其他任何内容都没有意义。

相反,请更改您的代码以遵循此模式

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 

答案 1 :(得分:1)

看起来在try / except块中调用代码中途的create_account()是问题所在,它会递归,返回到周围的代码,然后继续执行if / else再次阻止。 (可以解释输出的事件顺序)。

顺便说一下,这段代码的整体结构非常混乱,我怀疑这是因为你没有使用for循环或while循环而不是递归。此外,您应该尽可能避免使用global变量,因为它们也会混淆程序的控制流,尤其是递归。