python - Selenium Python - 如何引发异常并继续循环?
问题描述
如果发现任何不匹配,我想提出一个异常错误,但循环也应该继续。如果有任何不匹配/异常错误,整个案例都应该失败。你们可以检查下面的代码并在这里帮助我吗?
def test01_check_urls(self, test_setup):
#reading the file
Total_entries=len(old_urls) //Total_entries=5
print("Total entries in the sheet: "+ str(Total_entries))
col_count=0
#opening urls
while col_count<Total_entries:
Webpage=old_urls[col_count] //fetching data from 1st cell in the excel
Newpage=new_urls[col_count] //fetching data from 1st cell in the excel
driver.get(Webpage)
print("The old page url is: "+Webpage)
page_title=driver.title
print(page_title)
Redr_page=driver.current_url
print("The new url is: "+Redr_page)
print("New_url from sheet:"+Newpage)
try:
if Redr_page==Newpage:
print("Correct url")
except:
raise Exception("Url mismatch")
col_count+=1
解决方案
有一个变量url_mismatch
,最初False
。当 URL 不匹配时,不要立即引发异常,只需将此变量设置为True
. 然后当循环结束时,检查这个变量的值,如果变量是 ,则引发异常True
。
但是,尚不清楚您的try
块如何导致异常。您可能是说(不需要try
阻止):
if Redr_page == Newpage:
print("Correct url")
else:
raise Exception("Url mismatch")
现在我不修改那部分代码:
url_mismatch = False
while col_count<Total_entries:
Webpage=old_urls[col_count] //fetching data from 1st cell in the excel
Newpage=new_urls[col_count] //fetching data from 1st cell in the excel
driver.get(Webpage)
print("The old page url is: "+Webpage)
page_title=driver.title
print(page_title)
Redr_page=driver.current_url
print("The new url is: "+Redr_page)
print("New_url from sheet:"+Newpage)
try:
if Redr_page==Newpage:
print("Correct url")
except:
print('Mismatch url')
url_mismatch = True # show we have had a mismtach
col_count+=1
# now check for a mismatch and raise an exception if there has been one:
if url_mismatch:
raise Exception("Url mismatch")
推荐阅读
- javascript - TypeError:“data”参数必须是字符串类型或 Buffer、TypedArray 或 DataView 的实例。收到 IncomingMessage 的一个实例
- windows - 无法获得正确的打印机状态
- java - com.predic8.soamodel.TypeRefAccessException 在为 WSDL 创建 SOAP 请求模板时
- docusignapi - 签名工具不适用于嵌入式签名
- java - Android - Firebase 实时数据库参考指向无效的 url
- python - matplolib 子图的大小调整
- google-cloud-platform - 提交后,Google OAuth 同意屏幕停留在“需要验证”
- pandas - Python - Plotly,Dash 问题 - 基于值的自定义标签和颜色
- xcode - 为什么我不能使用 brew 命令安装 watchman?
- google-api - Google Drive watch API:如何设置请求标头/通知正文