使用 try except 在 python 中捕获错误

catching error in python using try except

我有以下代码:

from selenium.webdriver import Firefox
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
from selenium.common.exceptions import NoSuchElementException
import time

while True:
    try:
        
        url = 'https://finance.yahoo.com/'
        driver_path = 'C:\Users\inder\geckodriver.exe'
        
        browser = Firefox(executable_path = driver_path)
        browser.get(url)
        
        search_field_id = 'yfin-usr-qry'
        
        element_search_field = browser.find_element_by_id(search_field_id)
        element_search_field.clear()
        element_search_field.send_keys('TSLA')
        element_search_field.send_keys(Keys.ENTER)
        time.sleep(5)
        xpath_string = '/html/body/div[1]/div/div/div[1]/div/div[2]/div/div/div[6]/div/div/section/div/ul/li[2]/a/span'
        element = browser.find_element_by_xpath(xpath_string)
        action_chains = ActionChains(browser)
        action_chains.move_to_element(element).click().perform()
        break
    except NoSuchElementException as e:
        print(e)
        pass
    
    
   

此代码工作正常我正在尝试做的是如果由于某种原因如果页面未正确加载,我希望整个代码块再次 运行。 为此,我确定了搜索字段 element_search_field。如果通常找不到该元素,我会得到一个错误:

NoSuchElementException: Unable to locate element: /html/body/div[1]/div/div/div[1]/div/div[2]/div/div/div[6]/div/div/section/div/ul/li[2]/a/span

然而,当我尝试用上面的代码捕获这个异常时,我收到了一个错误:

NameError: name 'NoSuchElementException' is not defined

请告诉我如何解决这个问题。

你用pycharm吗?如果使用pycharm,会提示密码错误 你应该这样做。

from selenium.common.exceptions import NoSuchElementException

而且我在你的 code.It 中找不到声明变量 action_chains 好像是个错误

我自己没有遇到过这个问题,但 Selenium documentation lists 是常见的例外情况。所以也许你可以试试:

from selenium.common.exceptions import NoSuchElementException