【发布时间】:2021-08-05 01:07:03
【问题描述】:
我有以下代码:
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
请告知我可以做些什么来解决这个问题。
【问题讨论】:
-
似乎您缺少一些导入。可以查一下吗?
-
这是我的全部代码。您指的是哪些进口产品?
标签: python selenium error-handling try-catch