首页 > 解决方案 > Python - 尝试下一个 for 循环

问题描述

我有一个遍历 URL 列表的 for 循环。然后由 chrome 驱动程序加载 URL。一些 url 将加载一个“错误”格式的页面,它会在第一次 xpath 测试中失败。如果是,我希望它返回到循环中的下一个元素。我的清理代码有效,但我似乎无法让它进入 for 循环中的下一个元素。我有一个除了关闭我的 websbrowser 但我没有尝试过的所有内容然后循环回到 'for row in mysql_cats'

for row in mysql_cats : 
   print ('Here is the url -', row[1])
   cat_url=(row[1])
   driver = webdriver.Chrome()
   driver.get(cat_url); #Download the URL passed from mysql

   try:   
      CategoryName= driver.find_element_by_xpath('//h1[@class="categoryL3"]|//h1[@class="categoryL4"]').text   #finds either L3 or L4 catagory 
   except:
      driver.close()
      #this does close the webriver okay if it can't find the xpath, but not I cant get code here to get it to go to the next row in mysql_cats

标签: pythonfor-loop

解决方案


如果没有发生异常,我希望您在此代码末尾关闭驱动程序。
如果您想在引发异常时从循环的开头开始,您可以添加continue,如其他答案中所建议的:

try:   
    CategoryName=driver.find_element_by_xpath('//h1[@class="categoryL3"]|//h1[@class="categoryL4"]').text   #finds either L3 or L4 catagory 
except NoSuchElementException:
    driver.close()
    continue # jumps at the beginning of the for loop

由于我不知道您的代码,因此以下提示可能没用,但处理这种情况的常用方法是一个try/except/finally子句:

for row in mysql_cats : 
    print ('Here is the url -', row[1])
    cat_url=(row[1])
    driver = webdriver.Chrome()
    driver.get(cat_url); #Download the URL passed from mysql
    try:
        # my code, with dangerous stuff
    except NoSuchElementException:
        # handling of 'NoSuchElementException'. no need to 'continue'
    except SomeOtherUglyException:
        # handling of 'SomeOtherUglyException'
    finally: # Code that is ALWAYS executed, with or without exceptions
        driver.close()

我还假设您每次都在创建新驱动程序是有原因的。如果它不是自愿的,你可以使用这样的东西:

driver = webdriver.Chrome()
for row in mysql_cats : 
    print ('Here is the url -', row[1])
    cat_url=(row[1])
    driver.get(cat_url); #Download the URL passed from mysql
    try:
        # my code, with dangerous stuff
    except NoSuchElementException:
        # handling of 'NoSuchElementException'. no need to 'continue'
    except SomeOtherUglyException:
        # handling of 'SomeOtherUglyException'
driver.close()

这样,您只有一个驱动程序来管理您尝试在for循环中打开的所有页面

看看在处理连接和驱动程序时它是如何真正有用的。 作为脚注,我希望您注意在代码中我总是指定我期望的异常:捕获所有异常可能是危险的。顺便说一句,如果您简单地使用,可能没有人会死try/except/finally
except:


推荐阅读