在python中处理selenium异常和alertbox

2024-09-26 17:57:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用selenium进行一些自动化工作。对不起,描述得太长了。我是Python新手。 基本上有学生结果门户。我们需要输入一个座位号,然后点击OK按钮查看结果。单击submit(提交)按钮,将打开一个新窗口,其中使用html格式的表格显示结果

  1. 如果座位号无效,则打开警报框,指示座位号无效,并选择ok关闭

问题:

  1. 我想循环从1500到1600的卷数。如果1501卷号无效,则显示警报框。我想关闭alertbox并继续第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)

这是错误

enter image description here


Tags: toimportwebseleniumalertwindowoptionshandle
3条回答

需要记录的事项:

  1. 您不应该多次使用隐式等待
  2. 使用显式等待,或者在死机情况下使用time.sleep(),下面的代码我把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

您可以浏览下面的代码一次

我没有编辑你的代码,但它符合你的要求

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

您的代码有几个问题

  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()将失败-这是实际发生的情况,因为没有出现警报。
    我正在努力制作一个正确的代码,但是其他人给了你工作代码。因此,您可以阅读此处的说明和此处的工作代码:)

相关问题 更多 >

    热门问题