When element not found should print : not found, but i got error :
JavaScript
x
2
1
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@name='q']"}
2
Here is my script and the element ‘search’ doesn’t exist
JavaScript
1
15
15
1
import time
2
from selenium import webdriver
3
4
driver = webdriver.Chrome(executable_path=r"C:UsersSAMSUNGchromedriver.exe")
5
driver.get('https://facebook.com')
6
search = driver.find_element_by_xpath("//input[@name='q']")
7
time.sleep(15)
8
if search:
9
time.sleep(15)
10
print('found')
11
driver.find_element_by_xpath("//input[@name='q']").send_keys('test')
12
else:
13
print('not found')
14
pass
15
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.
JavaScript
1
18
18
1
from selenium.webdriver.support.ui import WebDriverWait
2
from selenium.webdriver.support import expected_conditions as EC
3
from selenium.webdriver import ActionChains
4
5
driver = webdriver.Chrome()
6
wait = WebDriverWait(driver, 20)
7
action = ActionChains(driver)
8
9
driver = webdriver.Chrome(executable_path=r"C:UsersSAMSUNGchromedriver.exe")
10
driver.get('https://facebook.com')
11
12
try:
13
search = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@name='q']")))
14
print('Element Found')
15
action.move_to_element(search).send_keys('test').perform()
16
except:
17
print("Element not Found")
18