首页 > 解决方案 > 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

标签: pythonseleniumpytest

解决方案


有一个变量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")

推荐阅读