【问题标题】:Handling selenium exceptions and alertbox in python在 python 中处理 selenium 异常和 alertbox
【发布时间】:2021-09-01 11:44:15
【问题描述】:

我正在使用 selenium 进行一些自动化工作。抱歉描述太长了。我是 Python 新手。 基本上有学生成绩门户。我们需要输入一个座位号,然后单击确定按钮查看结果。单击提交时会打开新窗口,其中使用 html 中的表格显示结果。

  1. 如果座位号无效,警报框会打开,指示座位号无效,然后关闭 ok 选项。

问题:

  1. 我想遍历从 1500 到 1600 的卷号。如果 1501 卷号无效,则会显示警报框。我想关闭警报框并继续使用第 1502 卷。

如果结果的值超过 96%,我想将计数增加 1。 2. 计算完结果打开后,我想关闭新打开的窗口,重新输入下一个座位号。继续计算

这是我的代码:

from selenium import webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.webdriver.common.alert import Alert
import time

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
web = webdriver.Chrome(options=options,executable_path='J:\stuff\soft\chromedriver.exe')
web.get('https://msbte.org.in/DISRESLIVE2021CRSLDSEP/frmALYSUM21PBDisplay.aspx')

# variable to store the result
resultCount = 0

rlstart = 156857
rlend = 157299

try:
    web.implicitly_wait(5)
    pdl  = web.current_window_handle
    for x in range(rlstart, rlend):

        web.implicitly_wait(1)
        inp = web.find_element_by_xpath('//*[@id="txtEnrollSeatNo"]')
        inp.send_keys(x)
        submit = web.find_element_by_xpath('//*[@id="btnSubmit"]')
        submit.click()

        web.implicitly_wait(2)
        web.implicitly_wait(2)

        # pdl  = web.current_window_handle
        handles =  web.window_handles
        for handle in handles:
            if(handle != pdl):
                switch_to_alert().accept()
                web.switch_to.window(handle)

                getresult = web.find_element_by_css_selector('body > div > div:nth-child(3) > div:nth-child(4) > table > tbody > tr:nth-child(5) > td:nth-child(3) > strong').text
                if(getresult > 96.00):
                    resultCount += 1
                web.close()
                web.switch_to.window(pdl)

    web.implicitly_wait(2)
    
except UnexpectedAlertPresentException:
    alert_obj = web.switch_to.alert
    alert_obj.accept()
    
    

finally:
    print("end")
    web.quit()
    print(resultCount)

这是错误

【问题讨论】:

    标签: python selenium exception automation


    【解决方案1】:

    你可以通过下面的代码一次。

    我没有编辑你的代码,但它可以满足你的要求。

    while rlstart != rlend+1: , rlend+1 因为如果有增量,156860 变为 156861 而当 rlstart156861 时,它会出现 while 循环并且不会给出 156861's 结果。

    from selenium import webdriver
    import time
    
    driver = webdriver.Chrome(executable_path="path")
    driver.maximize_window()
    driver.implicitly_wait(10)
    driver.get("https://msbte.org.in/DISRESLIVE2021CRSLDSEP/frmALYSUM21PBDisplay.aspx")
    rlstart = 156857
    rlend = 156860 # Have tested only for a few Seat no.
    #rlend = 157299
    while rlstart != rlend+1:
        try:
            driver.find_element_by_id("txtEnrollSeatNo").send_keys(rlstart) # To send the Seat no
            driver.find_element_by_id("btnSubmit").click() # To click on the submit button and exemption happens after this.
            # Collect all  the windows opened-up.
            handles = driver.window_handles
            # Switch to other window and extract the Seat no and percenatge.
            driver.switch_to.window(handles[1])
            time.sleep(1)
            seatno = driver.find_element_by_xpath("/html/body/div/div[2]/table/tbody/tr[2]/td[6]").text
            per = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/table/tbody/tr[5]/td[3]/strong").text
            print("Result of Seat no: {}".format(seatno))
            print("Percentage: {}".format(per))
            # Since percentage is in decimal but as a string, converting it into float is more accurate. Compare and increment.
            if float(per)>96.0:
                rlend+=1
                print("new rlend: {}".format(rlend))
            # Close the new window, switch back to parent window and clear before entering a new Seat no.
            driver.close()
            driver.switch_to.window(handles[0])
            driver.find_element_by_id("txtEnrollSeatNo").clear()
        except:
            print("Invalid Seat No : {}".format(rlstart))
            # Handle the alert, clear the field for next Seat no and continue. No need to switch between windows since no new window has opened up.
            driver.switch_to.alert.accept()
            driver.find_element_by_id("txtEnrollSeatNo").clear()
            pass
        rlstart+=1
    driver.quit()
    

    输出:

    Result of Seat no: 156857
    Percentage: 95.71
    Result of Seat no: 156858
    Percentage: 96.63
    new rlend: 156861
    Result of Seat no: 156859
    Percentage: 86.11
    Result of Seat no: 156860
    Percentage: 90.29
    Result of Seat no: 156861
    Percentage: 96.17
    new rlend: 156862
    Result of Seat no: 156862
    Percentage: 75.00
    

    【讨论】:

    • 虽然您的代码运行良好,但如果您可以添加一些关于您所做更改的解释,那将更加明显。这将使解决方案更容易理解。
    • @demouser123 - 是的,谢谢您的建议。已使用所需的 cmets 更新了代码。
    【解决方案2】:

    您的代码有几个问题。

    1. web.implicitly_wait(1) 不会在您的代码中插入实际的暂停。它只是设置超时。等待元素出现在页面上的时间。所以当你定义它两次时
    web.implicitly_wait(2)
    web.implicitly_wait(2)
    

    这不会让您暂停 4 秒,只是将超时时间定义为 2 秒两次,但不会暂停您的程序流程。
    此外,您不需要多次定义它,只需定义一次并忘记它。
    此外,我们通常将超时定义为 10-20-30 秒,而不是 1-2 秒。如果互联网连接速度慢/网站响应速度慢等情况,这可能会导致测试失败。

    1. 如果座位号正确,则不会出现警报,但数据会在新窗口中打开。
      因此,当座位正确时 switch_to_alert().accept() 将失败 - 这是实际发生的情况,因为没有出现警报。
      我正在努力制作正确的代码,但其他人给了你工作代码。所以你可以在这里阅读解释和那里的工作代码:)

    【讨论】:

    • 是的。谢谢你。我纠正的第二个错误。关于implicitly_wait。因为我们有 2 个窗口,如果我们在程序开始时添加一个等待语句,有 10 / 30 秒,它会应用于新窗口还是当前窗口?
    • AFAIK 它设置在 webdriver driver 对象上。所以它适用于该驱动程序管理的所有窗口。
    • @DhananjayGavali :直到浏览器实例处于活动状态,它才会存在,现在当您执行driver.close 时,它确实会杀死新打开的浏览器窗口。
    • 如果您使用driver.close 关闭第二个窗口,而第一个窗口仍然存在,driver 设置将保留。我们不会在这里关闭整个浏览器 driver.quit
    【解决方案3】:

    注意事项:

    1. 您不应多次使用隐式等待。
    2. 使用显式等待,或者在死机情况下使用time.sleep(),我将以下代码放入睡眠只是为了视觉目的。
    3. 您将字符串与错误的浮点数进行比较。
    4. 有一种方法可以切换窗口,警报请见下文。
    5. 另外,话虽如此,我不建议将implicitexplicit 混合使用。
    6. 我已经降低了rlend 的值,出于测试目的,你必须增加它,看看它是否有效。

    代码:-

    web  = webdriver.Chrome(driver_path)
    web.maximize_window()
    #web.implicitly_wait(50)
    web.get("https://msbte.org.in/DISRESLIVE2021CRSLDSEP/frmALYSUM21PBDisplay.aspx")
    wait = WebDriverWait(web, 20)
    
    resultCount = 0
    
    rlstart = 156857
    rlend = 156861
    
    #157299
    try:
        for x in range(rlstart, rlend):
            orginal_window = web.current_window_handle
            seat_input_box = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[id='txtEnrollSeatNo']")))
            time.sleep(1)
            seat_input_box.clear()
            seat_input_box.send_keys(rlstart)
            rlstart = rlstart + 1
            submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[id='btnSubmit']")))
            submit.click()
            try:
                print("Alert was not present, but new windows was")
                handles = web.window_handles
                web.switch_to.window(handles[1])
                time.sleep(1)
                web.maximize_window()
                time.sleep(2)
                web.execute_script("window.scrollTo(0, 300)")
                time.sleep(2)
                getresult = wait.until(EC.presence_of_element_located((By.XPATH, "//td[contains(text(),'Aggregate Marks : ')]/following-sibling::td[2]/strong"))).text
                getresult_dec = float(getresult)
                if getresult_dec > 96.00 :
                    resultCount = resultCount + 1
                    print("Kill the browser in else block.")
                    web.close()
                else:
                    web.close()
                    print("Kill the browser in else block.")
            except:
                print("Means alert is present. ")
                a = web._switch_to.alert
                a.accept()
                web.switch_to.default_content()
            time.sleep(3)
            web.switch_to.window(orginal_window)
    
    except:
        pass
    
    print(resultCount)
    

    进口:

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

    【讨论】:

    • 除了浮动比较之外,您对原始代码登录进行了很多更改。因此,我认为您还应该添加这些更改的摘要。另外我在两台不同的机器上运行了你的代码,它只在第一台机器上正确打开,然后新的浏览器窗口没有打开。
    • @demouser123 :我明白这一点,但由于这是一个非常具体的问题并且没有真正的普通观众,所以我没有说,但是你去吧,现在效果很好,请运行如果您遇到任何问题,请告诉我。
    • @Dhananjay Gavali :您现在可以运行代码,它似乎可以完美运行。此外,我实际上减少了rlend 以在我的本地进行测试,您可以增加该值并让我知道您在运行代码时是否遇到任何问题。
    • @cruisepandey :它没有识别 Webdriver 等等,您能否还添加导入语句应该如何包含它们。我是 python 新手
    • @DhananjayGavali : 请看上面我已经更新了。
    猜你喜欢
    • 2020-04-25
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2022-07-07
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    相关资源
    最近更新 更多