如果未找到元素,则继续执行脚本

Continue the script if an element is not found

平台上至少还有 2 个问题,但他们的 none 个回答对我有帮助。

我刚导入:

from selenium.common.exceptions import NoSuchElementException

然后使用:

if Newest_tab_button:
    print('element found')
else:
    print('not found')

try:
    wait = WebDriverWait(driver, 15)
    Newest_tab_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="NEWEST"]//ancestor::*[contains(@resource-id, "itemContainer")]')))
except NoSuchElementException:
    print('Element not found')

没有任何效果,仍然得到:

selenium.common.exceptions.TimeoutException: Message: 

有人可以帮我吗?提前致谢。

在第二种方法中,你只捕获了 NoSuchElementException,但问题是你的脚本超时了,你得到了一个 TimeoutException,你只需要也捕获它继续脚本

from selenium.common.exceptions import NoSuchElementException, TimeoutException

try:
    wait = WebDriverWait(driver, 15)
    Newest_tab_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="NEWEST"]//ancestor::*[contains(@resource-id, "itemContainer")]')))
except (NoSuchElementException, TimeoutException) as error:
    print(error)
# Continue with the script

您可以在同一个 except 块或多个 except 块中捕获多个异常

try:
    wait = WebDriverWait(driver, 15)
    Newest_tab_button = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="NEWEST"]//ancestor::*[contains(@resource-id, "itemContainer")]')))
except TimeoutException as e:
    print("TimeoutException")
    
except NoSuchElementException as e1:
    print("NoSuchElementException")
    
except Exception as e3: # To catch an Exception other than the specified once.
    print(e3)

或者您需要将所有异常放在一个元组中:

except (TimeoutException,NoSuchElementException): # This catches either TimeoutException or NoSuchElementException
    print("ERROR")