在 python 中处理 selenium 异常和警报框
Handling selenium exceptions and alertbox in python
我正在使用 selenium 进行一些自动化工作。很抱歉长描述。我是 Python 的新手。
基本上有学生成绩门户。我们需要在其中输入座位号,然后单击“确定”按钮以查看结果。单击提交后,将打开新的 window,其中使用 html 中的 table 显示结果。
- 如果座位号无效,则会打开警告框,指示座位号无效,然后可以关闭选项。
问题:
- 我想遍历从 1500 到 1600 的卷号。如果 1501 卷号无效,则会显示警告框。我想关闭警报框并继续滚动编号 1502。
如果结果的值大于 96%,我想将计数增加 1。
2. 计算完结果一打开我想关闭新打开的window,重新输入下一个座位号。并继续计算
这是我的代码:
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)
这是错误
注意事项:
- 您不应多次使用隐式等待。
- 使用显式等待,或者在死机情况下使用
time.sleep()
,下面的代码我只是为了视觉目的而放置睡眠。
- 您将字符串与浮点数进行比较是错误的。
- 有办法切换windows,请看下面的提示。
- 此外,话虽如此,我不建议将
implicit
与 explicit
混合使用。
- 我已经降低了
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
并且当 rlstart
是 156861
, 它来退出 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
您的代码存在几个问题。
web.implicitly_wait(1)
不会在您的代码中插入实际的暂停。它只是设置超时。等待元素出现在页面上的时间。所以当你定义它两次时
web.implicitly_wait(2)
web.implicitly_wait(2)
这不会让您暂停 4 秒,只是定义两次 2 秒的超时,但不会暂停您的程序流程。
而且你不需要多次定义这个,只定义一次就忘了它。
此外,我们通常将超时定义为 10-20-30 秒,而不是 1-2 秒。如果互联网连接速度慢/网站响应速度慢等,这可能会导致测试失败。
- 如果座位号正确,则不会出现警报,但数据会在新 window 中打开。
所以当座位正确时 switch_to_alert().accept()
将失败 - 这是因为没有出现警报而实际发生的情况。
我正在努力编写正确的代码,但其他人给了你工作代码。所以你可以在这里阅读解释和那里的工作代码:)
我正在使用 selenium 进行一些自动化工作。很抱歉长描述。我是 Python 的新手。 基本上有学生成绩门户。我们需要在其中输入座位号,然后单击“确定”按钮以查看结果。单击提交后,将打开新的 window,其中使用 html 中的 table 显示结果。
- 如果座位号无效,则会打开警告框,指示座位号无效,然后可以关闭选项。
问题:
- 我想遍历从 1500 到 1600 的卷号。如果 1501 卷号无效,则会显示警告框。我想关闭警报框并继续滚动编号 1502。
如果结果的值大于 96%,我想将计数增加 1。 2. 计算完结果一打开我想关闭新打开的window,重新输入下一个座位号。并继续计算
这是我的代码:
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)
这是错误
注意事项:
- 您不应多次使用隐式等待。
- 使用显式等待,或者在死机情况下使用
time.sleep()
,下面的代码我只是为了视觉目的而放置睡眠。 - 您将字符串与浮点数进行比较是错误的。
- 有办法切换windows,请看下面的提示。
- 此外,话虽如此,我不建议将
implicit
与explicit
混合使用。 - 我已经降低了
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
并且当 rlstart
是 156861
, 它来退出 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
您的代码存在几个问题。
web.implicitly_wait(1)
不会在您的代码中插入实际的暂停。它只是设置超时。等待元素出现在页面上的时间。所以当你定义它两次时
web.implicitly_wait(2)
web.implicitly_wait(2)
这不会让您暂停 4 秒,只是定义两次 2 秒的超时,但不会暂停您的程序流程。
而且你不需要多次定义这个,只定义一次就忘了它。
此外,我们通常将超时定义为 10-20-30 秒,而不是 1-2 秒。如果互联网连接速度慢/网站响应速度慢等,这可能会导致测试失败。
- 如果座位号正确,则不会出现警报,但数据会在新 window 中打开。
所以当座位正确时switch_to_alert().accept()
将失败 - 这是因为没有出现警报而实际发生的情况。
我正在努力编写正确的代码,但其他人给了你工作代码。所以你可以在这里阅读解释和那里的工作代码:)