Kaushal28
Kaushal28

Reputation: 5557

Selenium can't find elements even if they exist

I'm creating a simple selenium script to enter username and password to log in. Here is my code:

driver = webdriver.Chrome(executable_path=r'C:\\Users\\Aspire5\\Downloads\\chromedriver_win32\\chromedriver.exe')
driver.get("https://ven02207.service-now.com/")

username = driver.find_element_by_xpath('//*[@id="user_name"]')
username.send_keys('username')

password = driver.find_element_by_xpath('//*[@id="user_password"]')
password.send_keys('this_is_password')

But I'm getting following exception:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="user_name"]"}

I'm accessing this website from code. The XPath I've provided in code are exists on the page, but still it's returning No Such Element Exception.

What I'm missing here? I've seen this, this questions for this, but couldn't find exact answer.

Upvotes: 3

Views: 12111

Answers (3)

iamklaus
iamklaus

Reputation: 3770

you need to first switch to the frame.. since the input tag is inside the frame

frame = driver.find_element_by_xpath('//*[@id="gsft_main"]')
driver.switch_to.frame(frame)
driver.find_element_by_id('user_name').send_keys('sarthak')
driver.find_element_by_id('user_password').send_keys('sarthak')

Upvotes: 6

anish
anish

Reputation: 88

Just use escape slashes and you'll be fine

'//*[@id=\"user_name\"]'
'//*[@id=\"user_password\"]'

Upvotes: 0

Ankur Singh
Ankur Singh

Reputation: 1289

You need to wait for element to present in DOM. So try to wait before getting web element driverwebdriver.Chrome(executable_path=r'C:\Users\Aspire5\Downloads\chromedriver_win32\chromedriver.exe')

driver.get("https://ven02207.service-now.com/")

username = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//*[@id="user_name"]"))
username.send_keys('username')

password = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="user_password"]'))
password.send_keys('this_is_password')    

Upvotes: 0

Related Questions