使用try方法下的if/else来登录,然而成功登录会引发异常。

huangapple go评论70阅读模式
英文:

Using if/else under a try method to login, however a successful login throws exception

问题

以下是您提到的代码片段中的翻译部分:

print(f"The stripped captcha text is: {result}")
time.sleep(1)
if result:
    try:
        driver.find_element(By.XPATH, "//div[@id='app']//div[contains(@class, 'el-input')]//input[@name='captcha']").send_keys(result)
        driver.find_element(By.XPATH, "//div[@id='app']//button[contains(@type,'button')]").click()
        print("Captcha has been entered")
        time.sleep(2)
        login_button = driver.find_element(By.XPATH, "//div[@id='app']//form[@class= 'el-form login-form el-form--label-left']//button[contains(@type,'button')]")
        if login_button:
            #try again by page refresh
            print("Captcha was entered but was wrong, trying again...")
            driver.refresh()
            login_attempt()
        else:
            print("The login attempt worked!")
    except:
        print("Seems to me that you are already logged in, but I will keep repeating this until you solve this loop")
        time.sleep(2)
        login_button = driver.find_element(By.XPATH, "//div[@id='app']//form[@class= 'el-form login-form el-form--label-left']//button[contains(@type,'button')]")
        if login_button:
            #try again by page refresh
            print("Even after being logged in, trying again...this is not right.")
            driver.refresh()
            login_attempt()
        else:
            print("The login attempt may have worked!")
else:
    print("The captcha result was maybe blank.")
    time.sleep(2)
    if login_button:
        #try again by page refresh
        driver.refresh()
        time.sleep(2)
        login_attempt()
    else:
        print("The login attempt worked!")

示例输出:

Login button was found and variable has been recorded
Login attempt was called by your code
Username and Password were entered
The stripped captcha text is: vyiw4
Captcha has been entered
Captcha was entered but was wrong, trying again...
Login attempt was called by your code
Username and Password were entered
The stripped captcha text is: fhxax
Captcha has been entered
Seems to me that you are already logged in, but I will keep repeating this until you solve this loop
Seems to me that you are already logged in, but I will keep repeating this until you solve this loop

关于您的问题,代码中的以下部分:

else:
    print("The login attempt worked!")

看起来只有在没有任何异常抛出的情况下才会执行。如果在执行登录后发生异常,它将不会被执行。您可能需要检查异常的类型,并相应地处理。

英文:

Here is the snippet of the code I think is having a loop bug. I have been successful in having it retry upon failure or blank entry.
But once it logs in, it still keeps trying to login. Could someone take a look?

print(f"The stripped captcha text is: {result}")
time.sleep(1)
if result:
    try:
        driver.find_element(By.XPATH,"//div[@id='app']//div[contains(@class, 'el-input')]//input[@name='captcha']").send_keys(result)
        driver.find_element(By.XPATH,"//div[@id='app']//button[contains(@type,'button')]").click()
        print("Captcha has been entered")
        time.sleep(2)
        login_button = driver.find_element(By.XPATH,"//div[@id='app']//form[@class= 'el-form login-form el-form--label-left']//button[contains(@type,'button')]")
        if login_button:
            #try again by page refresh
            print("Captcha was entered but was wrong, trying again...")
            driver.refresh()
            login_attempt()
        else:
            print("The login attempt worked!")
    except:
        print("Seems to me that you are already logged in, but I will keep repeating this until you solve this loop")
        time.sleep(2)
        login_button = driver.find_element(By.XPATH,"//div[@id='app']//form[@class= 'el-form login-form el-form--label-left']//button[contains(@type,'button')]")
        if login_button:
            #try again by page refresh
            print("Even after being logged in, trying again...this is not right.")
            driver.refresh()
            login_attempt()
        else:
            print("The login attempt may have worked!")
else:
    print("The captcha result was maybe blank.")
    time.sleep(2)
    if login_button:
        #try again by page refresh
        driver.refresh()
        time.sleep(2)
        login_attempt()
    else:
        print("The login attempt worked!")

Sample Output:

Login button was found and variable has been recorded
Login attempt was called by your code
Username and Password were entered
The stripped captcha text is: vyiw4
Captcha has been entered
Captcha was entered but was wrong, trying again...
Login attempt was called by your code
Username and Password were entered
The stripped captcha text is: fhxax
Captcha has been entered
Seems to me that you are already logged in, but I will keep repeating this until you solve this loop
Seems to me that you are already logged in, but I will keep repeating this until you solve this loop

I tried to implement a re-attempt at failure logic, but failed to implement a successful scenario logic. I have no clue how to avoid the code to keep retrying, it is almost as if it skips the below else condition:

else:
    print("The login attempt worked!")

答案1

得分: 0

我添加了一条评论,但觉得我应该添加一个响应以更清楚。我假设这是selenium - 如果是这样,你应该将它标记为这样。我另一个假设是,在成功登录后,登录按钮不会出现。

我看到的主要问题是你没有处理元素不存在的情况,而是假设 login_button 始终为 True/False,但实际上它会抛出 NoSuchElementException 异常。此外,你的重试逻辑似乎过于循环。

在你的示例中:

  • 如果找到验证码:尝试登录
  • 如果找不到验证码:尝试登录
  • 如果登录似乎成功:尝试登录

在什么情况下会停止尝试登录呢?

尝试像这样做:

from selenium.common.exceptions import NoSuchElementException

print(f"The stripped captcha text is: {result}")
time.sleep(1)
if result:
    driver.find_element(By.XPATH,"//div[@id='app']//div[contains(@class, 'el-input')]//input[@name='captcha']").send_keys(result)
    driver.find_element(By.XPATH,"//div[@id='app']//button[contains(@type,'button')]").click()
    print("Captcha has been entered")
    time.sleep(2)
    try:
        login_button = driver.find_element(By.XPATH,"//div[@id='app']//form[@class= 'el-form login-form el-form--label-left']//button[contains(@type,'button')]")
        if login_button:
            #尝试通过刷新页面再次登录
            print("Captcha was entered but was wrong, trying again...")
            driver.refresh()
            login_attempt()
    except NoSuchElementException:
        print("The login attempt worked!")
else:
    #进一步检查登录状态或假设用户已经登录

此外,你可以使用 selenium 的 WebDriverWait 而不是等待固定的 2 秒:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)  #10 秒的超时时间
wait.until(EC.visibility_of_element_located((By.XPATH, "XPATH STRING")))
#继续代码
英文:

I added a comment but figured I'd add a response to be more clear. I'm assuming this is selenium- if so you should tag it as such. The other assumption I am making is that the login button is not present after a successful login.

The main issue I see is that you are not handling the element not being present and assuming login_button will always be True/False, but in reality it will throw a NoSuchElementException. Also, it appears that your retry logic is too circular.

In your example:

  • If captcha is found: try logging in
  • If captcha is not found: try logging in
  • If login appears to be successful: try logging in

In what scenario would it stop attempting to login?

Try something like this:

from selenium.common.exceptions import NoSuchElementException

print(f"The stripped captcha text is: {result}")
time.sleep(1)
if result:
    driver.find_element(By.XPATH,"//div[@id='app']//div[contains(@class, 'el-input')]//input[@name='captcha']").send_keys(result)
    driver.find_element(By.XPATH,"//div[@id='app']//button[contains(@type,'button')]").click()
    print("Captcha has been entered")
    time.sleep(2)
    try:
        login_button = driver.find_element(By.XPATH,"//div[@id='app']//form[@class= 'el-form login-form el-form--label-left']//button[contains(@type,'button')]")
        if login_button:
            #try again by page refresh
            print("Captcha was entered but was wrong, trying again...")
            driver.refresh()
            login_attempt()
    except NoSuchElementException:
        print("The login attempt worked!")
else:
    #further check login status or assume user is already logged in

Also, instead of waiting a fixed 2s you could also utilize selenium's WebDriverWait:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)  #10s timeout
wait.until(EC.visibility_of_element_located((By.XPATH, "XPATH STRING")))
#continue code

huangapple
  • 本文由 发表于 2023年7月17日 23:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705900.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定