Home > database >  Unable to locate element for email text box when trying to log in to twitter using Selenium in Pytho
Unable to locate element for email text box when trying to log in to twitter using Selenium in Pytho

Time:03-06

Can somebody please explain to me as to why this method is not working?

Previously I was using this way to enter the email on the twitter login page, and it was able to work.

email = bot.find_element_by_xpath(
        '//*[@id="layers"]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input'
    )
    # sends the email to the email input
    email.send_keys(self.email)
    # executes RETURN key action
    email.send_keys(Keys.RETURN)

But now it is not working and it returns this error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="layers"]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div1/div/div[5]/label/div/div[2]/div/input"}

So I have tried to copy the xpath again from the twitter login website as shown in the following image: Copy the Xpath for username text box

And perform the following modifications for the code:

email = bot.find_element_by_xpath(
        '//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div[1]/div/div/div[5]/label/div/div[2]/div/input'
    )
    # sends the email to the email input
    email.send_keys(self.email)
    # executes RETURN key action
    email.send_keys(Keys.RETURN)

And I still ended up with the same unable to locate element error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div1/div/div/div[5]/label/div/div[2]/div/input"}

I am still a beginner in using Selenium and would like to know why this is happening and a possible workaround for this issue. Thank you so much for taking the time to read this!

CodePudding user response:

You should never use locaters automatically created by browser dv tools.
They are extremely fragile and not reliable as you see yourself.
For the username field there you can use this locator:

//input[@autocomplete='username']

So your selenium command can be

email = bot.find_element_by_xpath('//input[@autocomplete="username"]')

I advice you to learn how to create correct locators.
There are several tutorials about this, for example you can find here some of them

  • Related