Skip to content
Advertisement

Python Selenium Element Not Found

When element not found should print : not found, but i got error :

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name='q']"}

Here is my script and the element ‘search’ doesn’t exist

import time
from selenium import webdriver

driver = webdriver.Chrome(executable_path=r"C:UsersSAMSUNGchromedriver.exe")
driver.get('https://facebook.com')
search = driver.find_element_by_xpath("//input[@name='q']")
time.sleep(15)
if search:
    time.sleep(15)
    print('found')
    driver.find_element_by_xpath("//input[@name='q']").send_keys('test')
else:
    print('not found')
    pass

Didn’t work because we can’t do len to element ( we can do it only to elements with an s )

Advertisement

Answer

Try the below code and let me know if it works.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 20)
action = ActionChains(driver)

driver = webdriver.Chrome(executable_path=r"C:UsersSAMSUNGchromedriver.exe")
driver.get('https://facebook.com')

try:
    search = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@name='q']")))
    print('Element Found')
    action.move_to_element(search).send_keys('test').perform()
except:
    print("Element not Found")
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement