Reputation: 1200
I have the following code:
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
This code works fine what i am trying to do is if for some reason if the page has not loaded correctly, i would like the entire code block to run again.
To do this i have identified the search field element_search_field
. If the element is not found ordinarily i would get an error:
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
However when i try to catch this exception with my above code i am getting an error:
NameError: name 'NoSuchElementException' is not defined
Please advise what can I do to resolve this issue.
Upvotes: 0
Views: 1132
Reputation: 532
I haven't had this problem myself but the Selenium documentation lists the common exceptions. So maybe you can try:
from selenium.common.exceptions import NoSuchElementException
Upvotes: 1
Reputation: 132
Do you use pycharm? If you use pycharm,It will remind you that the code is wrong You should do this.
from selenium.common.exceptions import NoSuchElementException
And i can't find the declare variable action_chains in your code.It's like a mistake
Upvotes: 1