如何在for循环的if语句中终止执行并跳转至下一个URL?
如何在Selenium循环中终止当前迭代并跳转下一个URL?
看起来你想在检测到Error元素时,停止处理当前URL,直接切换到数组里的下一个URL,但你用的break其实会直接跳出整个循环,这就是代码出问题的核心原因。另外你的代码里还有个小坑:Error = driver.find_element_by_xpath("xpath")如果找不到这个元素,会直接抛出异常,根本走不到if Error:的判断逻辑。
我给你调整一下代码,解决这两个问题:
首先,要实现只跳过当前URL,继续处理下一个,你需要用continue而不是break——continue的作用就是跳过当前循环剩余的所有代码,直接进入下一次循环(也就是处理下一个URL)。
然后,针对Error元素的存在性判断,推荐用find_elements_by_xpath(复数形式),因为它找不到元素时不会抛出异常,只会返回一个空列表,这样你可以安全地判断元素是否存在。
修改后的代码如下:
for url in ArrayOfUrls: driver.get(url) try: elem1 = driver.find_element_by_xpath("xpath") elem1.click() except: print("elem1 not found") try: elem2 = driver.find_element_by_xpath("xpath") elem2.click() # 用find_elements判断Error元素是否存在,避免抛异常 error_elements = driver.find_elements_by_xpath("xpath") if error_elements: # 列表非空则说明元素存在 print("Error detected, moving to next URL") continue # 跳过当前迭代,直接处理下一个URL except: print("elem2 not found") # 这里可以添加当前URL正常完成后的其他操作
额外提个优化点:尽量不要用裸except(不指定异常类型),最好捕获Selenium的具体异常,比如NoSuchElementException,这样能避免捕获到其他无关的错误,调试起来更方便:
from selenium.common.exceptions import NoSuchElementException for url in ArrayOfUrls: driver.get(url) try: elem1 = driver.find_element_by_xpath("xpath") elem1.click() except NoSuchElementException: print("elem1 not found") try: elem2 = driver.find_element_by_xpath("xpath") elem2.click() error_elements = driver.find_elements_by_xpath("xpath") if error_elements: print("Error detected, moving to next URL") continue except NoSuchElementException: print("elem2 not found")
这样调整后,当检测到Error元素时,就会立刻停止当前URL的后续操作,直接加载数组里的下一个URL,完全符合你的需求。
内容的提问来源于stack exchange,提问作者M.Naveed
相关产品推荐
相关产品推荐

