This Python script demonstrates how to automate posting a tweet on Twitter using the Selenium web automation library. It opens a Chrome web browser, logs into a Twitter account, composes a tweet, and posts it.
Before running the script, make sure you have the following prerequisites installed:
Selenium library installed. You can install it using pip
:
pip install selenium
Google Chrome browser installed.
Import the necessary libraries:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time, os
Configure Chrome options to store cookies and start the browser maximized:
options = Options()
options.add_argument(f"user-data-dir={os.getcwd()}cookies")
options.add_argument("start-maximize")
user-data-dir
argument is used to specify the directory to store user data, including cookies, to maintain your Twitter login session.Create a Chrome webdriver instance:
driver = webdriver.Chrome(options=options)
Navigate to the Twitter website:
driver.get("https://twitter.com")
Wait for the Twitter page to load:
time.sleep(2)
Locate the tweet input field and send a tweet:
sendmessage = driver.find_element_by_xpath("*//*[@contenteditable='true']")
sendmessage.send_keys("test")
Find and click the tweet button:
kliktweet = driver.find_element_by_xpath("//div[@data-testid='tweetButtonInline']")
kliktweet.click()
Wait for a specified time (e.g., 60 seconds) to ensure the tweet is posted:
time.sleep(60)
Quit the Chrome driver:
driver.quit()
Customize the script to meet your specific automation needs, such as logging in with your Twitter account and posting the desired content.
os.getcwd()
with the appropriate directory path if needed.This script is provided under the MIT License.
You can customize the script and README.md file further to suit your specific requirements and ensure you have the correct WebDriver for Chrome installed.