3

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.

Kaushal28
  • 5,377
  • 5
  • 41
  • 72

3 Answers3

6

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')
iamklaus
  • 3,720
  • 2
  • 12
  • 21
  • Perfect! But how would I know when to switch to a frame and when not? +1 and will accept – Kaushal28 Oct 11 '18 at 16:26
  • 1
    so you will have to take a look, is the iframe used and if yes then is the code you want to scrape inside it... – iamklaus Oct 11 '18 at 16:35
  • 1
    you just saved my life! thanks for the answer and for the explanation, it is all clear to me now. spent several hours looking for this help, and finally found it. thank you again! – Zopy Mar 24 '20 at 07:22
0

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')    
Ankur Singh
  • 1,239
  • 1
  • 8
  • 18
0

Just use escape slashes and you'll be fine

'//*[@id=\"user_name\"]'
'//*[@id=\"user_password\"]'
anish
  • 88
  • 6