Home > Software design >  Can't log in to twitter with selenium: Python
Can't log in to twitter with selenium: Python

Time:12-13

I'm trying to log in to twitter with a bot.

self.browser.get('https://www.twitter.com/login') 
sleep(20)  
username_input = self.browser.find_element(By.XPATH,'//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input')
sleep(20)
username_input.send_keys(username)
sleep(5)

But I keep getting No Such Element error:

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]/div[1]/div/div[5]/label/div/div[2]/div/input"}

I copied and pasted the exact Xpath and I can't figure out why it can't find the field.

CodePudding user response:

I see name='text' is unique in HTML DOM. So there is no need to use XPath.

username_input = self.browser.find_element(By.NAME, "text")
username_input.send_keys('send username here')

A way better approach will be to induce ExplicitWait.

Code:

self.browser.maximize_window()
wait = WebDriverWait(self.browser, 30)
self.browser.get('https://www.twitter.com/login')

username_input = wait.until(EC.visibility_of_element_located((By.NAME, "text")))
username_input.send_keys('send username here')

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

CSS selector will be:

input[name='text']

XPATH will be:

//input[@name='text']

to use them, instead of By.NAME please use By.CSS_SELECTOR or By.XPATH

  • Related