Home > front end >  Python-Selenium no such element: Unable to locate element
Python-Selenium no such element: Unable to locate element

Time:11-23

I'm new to coding. I'am trying to make a twitter bot but when I find XPaths and paste it in my code it gives an error

I tried to find the element with id, name, selector and paste it in my code but none of them worked

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time



class TwitterBot:
    def __init__(self , username , password) :
        self.username = username
        self.password = password


        chrome_options = Options()
        self.bot = webdriver.Chrome(ChromeDriverManager().install() , options = chrome_options)


    def login(self):

        bot = self.bot
        bot.get("https://twitter.com/login")
        time.sleep(5)

        email = bot.find_element(By.XPATH , '/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[5]/label[1]/div[1]/div[2]/div[1]/input[1]')
        email.send_keys(self.username)


        


f = TwitterBot("blabla" ,"blabla")
f.login()

CodePudding user response:

You need to learn how to create correct, short and unique locators. Very long absolute XPaths and CSS Selectors are extremely breakable.
Also you need to use WebDriverWait expected_conditions explicit waits, not a hardcoded delays.
The following code works:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_argument('--disable-notifications')

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

url = "https://twitter.com/login"
driver.get(url)

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[autocomplete='username']"))).send_keys("ku-ku")

The result is:
enter image description here

  • Related