Selenium Python如何引发异常并继续循环?

2024-06-16 14:21:29 发布

您现在位置: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

Tags: theinfromurldrivercountpagecol
1条回答
网友
1楼 · 发布于 2024-06-16 14:21:29

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

相关问题 更多 >