Twitter (X) login using Selenium triggers anti-bot detection

1.4k views Asked by At

I am currently working on automating the login process for my Twitter account using Python and Selenium.

However, I'm facing an issue where Twitter's anti-bot measures seem to detect the automation and immediately redirect me to the homepage when clicking the next button.

Next button

I have attempted to use send_keys and ActionChains to create more human-like interactions, but the problem persists.

Here's a simplified code snippet that illustrates my current approach:

# imports...

driver.get(URLS.login)

username_input = driver.find_element(By.NAME, 'text')
username_input.send_keys(username)

next_button = driver.find_element(By.XPATH, '//div[@role="button"]')

# These attempts all failed and return to the homepage
next_button.click()
next_button.send_keys(Keys.ENTER)
ActionChains(driver).move_to_element(next_button).click().perform()

What's weird is that besides manually clicking the next button, execute a click in console also works.

I suspect that my automation attempts are still being detected by Twitter's security mechanisms, but I'm unsure about the root cause or how to bypass it successfully.

1

There are 1 answers

1
Ajeet Verma On BEST ANSWER

You may try this to log in to Twitter:

import time
from selenium import webdriver
from selenium.webdriver import ChromeOptions, Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


options = ChromeOptions()
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])

driver = webdriver.Chrome(options=options)
url = "https://twitter.com/i/flow/login"
driver.get(url)

username = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[autocomplete="username"]')))
username.send_keys("your_username")
username.send_keys(Keys.ENTER)

password = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'input[name="password"]')))
password.send_keys("your_password")
password.send_keys(Keys.ENTER)

time.sleep(10)

reference: