pythonhtmlxmlseleniumxpath

NoSuchElementException: no such element: Unable to locate element


Disclaimer: I'm coming back to scripting after more than a decade so apologies in advance for such a basic question but help is much needed and appreciated.

I recently tried to find scripts to automate my job hunt, to that end I found a script that would help me login to a job portal and apply to jobs matching my criteria.

But I believe the script is not updated because I'm coming across an error when I'm running it:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="root"]/div[2]/div[2]/div/form/div[2]/input"} (Session info: chrome=98.0.4758.109)

I believe this is in regard to the following lines of code:

driver.get("https://www.naukri.com")
driver.find_element_by_xpath('//*[@id="login_Layer"]/div').click()
time.sleep(5)
driver.find_element_by_xpath('//*[@id="root"]/div[2]/div[2]/div/form/div[2]/input').send_keys("YOUR NAUKRI LOGIN ID")
driver.find_element_by_xpath('//*[@id="root"]/div[2]/div[2]/div/form/div[3]/input').send_keys("YOUR NAUKRI PASSWORD")
time.sleep(5)
driver.find_element_by_xpath('//*[@id="root"]/div[2]/div[2]/div/form/div[6]/button').click()

The script is able to go to Naukri.com (the job portal) and find the path for login_Layer ID, which opens the login sidebar. But then it is not able to find the username and password field. Maybe because the webpage has changed.

I'm trying to inspect the page elements and find the right xpath but having no luck. Again, haven't touched XML/HTML or web development of any kind for over a decade (and was a novice to begin with) so finding it hard.

Any guidance or help will be really appreciated.

Looking forward to your answers.

Thanks in advance!


Solution

  • Yeah your XPaths are outdated.

    If you are on a chromium browser, right click on the element you want the XPath for and click inspect. If your DevTools are not yet open, do this twice. Then it will highlight your element in the page source. After that do a right click on the highlighted element, copy, and "Copy XPath" to update your script.

    driver.find_element_by_xpath('//*[@id="root"]/div[2]/div[2]/div/form/div[2]/input').send_keys("YOUR NAUKRI LOGIN ID")
    

    This syntax should still work, but modern guidelines want you to use this:

    from selenium.webdriver.common.by import By
    
    driver.find_element(By.XPATH, '//*[@id="root"]/div[3]/div[2]/div/form/div[2]/input').send_keys("YOUR NAUKRI LOGIN ID")