Code: Select all
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import config
class TweeterChromeConnector:
def __init__(self):
# open chrome
self.driver = webdriver.Chrome()
self.driver.get("https://twitter.com/login")
self.wait = WebDriverWait(self.driver, 20)
def login(self, user_name, password):
try:
# send user
span_element = self.wait.until(
EC.presence_of_element_located((By.XPATH, "//span[text()='Phone, email address, or username']")))
input_element = span_element.find_element(By.XPATH, "./ancestor::div[contains(@class, 'r-')]/following::input")
input_element.send_keys(user_name)
# press Next
span_element = self.driver.find_element(By.XPATH, "//span[text()='Next']")
button_element = span_element.find_element(By.XPATH, "./ancestor::span[contains(@class, 'r-')]")
button_element.click()
# handle password
span_element = self.wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Password']")))
input_element = span_element.find_element(By.XPATH, "./ancestor::div[contains(@class, 'r-')]/following::input")
input_element.send_keys(password)
# click login
span_element = self.wait.until(EC.presence_of_element_located((By.XPATH, "//span[text()='Log in']")))
button_element = span_element.find_element(By.XPATH, "./ancestor::span[contains(@class, 'r-')]")
button_element.click()
except Exception as e:
print(f"An error occurred during login: {e}")
raise
def post_tweet(self, post_txt):
try:
# Locate the tweet button and wait until it is clickable
post_button = self.wait.until(
EC.element_to_be_clickable((By.XPATH, "//a[@data-testid='SideNav_NewTweet_Button']"))
)
post_button.click()
# Write tweet
placeholder_element = self.wait.until(
EC.presence_of_element_located((By.XPATH, "//div[@data-testid='tweetTextarea_0_label']"))
)
input_element = placeholder_element.find_element(By.XPATH,
"//div[@class='public-DraftStyleDefault-block public-DraftStyleDefault-ltr']")
# Click on the input element to focus it
ActionChains(self.driver).move_to_element(input_element).send_keys(post_txt).perform()
# Locate the post button and wait until it is clickable
post_button = self.wait.until(
EC.element_to_be_clickable((By.XPATH, "//button[@data-testid='tweetButton']"))
)
# Wait until the button is enabled
self.wait.until(lambda driver: post_button.is_enabled())
post_button.click()
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == '__main__':
tc = TweeterChromeConnector()
tc.login(user_name=config.TWITTER_USER_NAME, password=config.TWITTER_PASSWORD)
tc.post_tweet('check eng 🏴')
tc.post_tweet('check sct 🏴')
tc.post_tweet('check wls 🏴')
print('done')