1

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()

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

4 Comments

firstly thanks. How can I learn about the things you do. Or can you give me your contact address? I need more help :)
There are a lot of tutorials in the internet. In case you want to contact me there is a private chat room link on my profile page
link dont work.
Hm... OK, you can write me to this FB fake account messenger facebook.com/profile.php?id=100011831197069

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.