In this article I’m going to explain how to create a Python Selenium Twitter bot. This bot will automate your browser and post tweets automatically using the Selenium tool. This method doesn’t rely on any Twitter or third party API. Instead it tweets on your behalf using browser automation from scratch.
We are going to create a simple bot with a single job. Every day it will pick an item from a list of texts that we provided and then tweet it. The bot will launch the browser by itself, navigate to the Twitter homepage and then post the tweet from the web interface.
For creating this simple bot we only need a web browser, a webdriver to control the browser, a library to run that webdriver, and the mighty Python to glue it all together. If you are interested you might want to look into the Python Automation Tools article to learn about some of the most commonly used tools in Python automation.
The first thing you’ll need to create a Python Selenium Twitter bot is ensure that you have a Twitter account. We are going to need the username and password details of that account and we will assume the values to be EMAIL and PASSWORD respectively in the rest of this article.
The first task we want to do with our Python Selenium Twitter bot is to log in to our account. You have to keep in mind that the web browser session that we will spawn using our Python program will run in an isolated mode, kind of like the incognito mode where each session is independent and the cookies or other information is not stored by the browser. This means every time you run the program you will have to log in again.
Let’s start with installing the two needed libraries: Selenium and PyAutoGUI
pip install selenium pyautogui
We are going to use Firefox and its webdriver known as geckodriver for this tutorial. You are free to use Chrome or any other browser and download the corresponding webdriver (eg Chromedriver). You can download the appropriate geckodriver binary for your Firefox version and operating system from this page.
After downloading and extracting the geckodriver binary put it in the same folder where you are going to keep your code for this Python Selenium twitter bot. Now let’s get to coding. I’ll share the entire code with you and then explain how I went about writing it.
import os import time from selenium import webdriver from selenium.webdriver.common.keys import Keys import pyautogui def find_by_text(driver, text): return driver.find_element_by_xpath("//*[contains(text(), '%s')]" % text) def find_form_ele(driver, text): uele = driver.find_element_by_xpath("//*[contains(text(), '%s')]" % text) uele = uele.find_element_by_xpath("..") return uele.find_element_by_xpath("./following-sibling::div/div/input") def run(): print("Started") usr_pwd = os.environ.get("PWD") or input("password: ") cur_dir = os.getcwd() geckopath = os.path.join(cur_dir, "geckodriver") driver = webdriver.Firefox(executable_path=geckopath) driver.get("https://twitter.com") time.sleep(5) uele = find_form_ele(driver, "Phone, email, or username") uele.send_keys("EMAIL") uele = find_form_ele(driver, "Password") uele.send_keys(usr_pwd) time.sleep(1) uele.submit() time.sleep(3) fele = driver.find_element_by_css_selector(".notranslate > div:nth-child(1) > div:nth-child(1)") fele = fele.find_element_by_xpath("./div") fele.click() time.sleep(1) pyautogui.write(""" “This is a cool quote! """) pyautogui.press(['tab'] * 6) pyautogui.press('enter') time.sleep(6) fele.submit() driver.quit() if __name__ == "__main__": run()
The first thing we do is import the webdriver package from selenium library.
The entry point of code is in the run function. First we obtain the password
from either the environment variable or ask user for the input. Then we
initialize the driver by creating a Firefox webdriver object:
driver = webdriver.Firefox(executable_path=geckopath)
The first thing we want our browser automater to do is visit
Then we look for the element in browser’s DOM containing the text
“Phone, email, or username” as the corresponding element is
situated adjacent to the username field which we need to fill. The username
input field is a sibling of the parent of the aforementioned field and we have
created a function which will find us the input field based on the adjacent
element. After locating the element we automate sending key presses to the
browser and enter the email:
Similarly we locate the password field and fill the password. Following that we submit the associated log in form. We also put in random sleeps at a few places. Once the log in form is filled and submitted we’ll be redirected to the Twitter home page where we can post our tweet. We find the relevant element responsible for accepting the user input to post a tweet using these lines:
fele = driver.find_element_by_css_selector(".notranslate > div:nth-child(1) > div:nth-child(1)") fele = fele.find_element_by_xpath("./div")
After locating the right element we click on it to get it on focus and be able
to write in it. Here you will note that Twitter doesn’t make it easy to
write in the form. Reason being that the box isn’t an input field but
some complex JS element. Therefore we use another library called PyAutoGUI to
enter our tweet as Selenium will otherwise complain that the input field
isn’t visible. We type in the tweet using this statement:
pyautogui.write("""This is a cool quote!
After that we locate the “Submit” button by navigating across the menu buttons by pressing TAB button six times. We follow it by pressing the ENTER button. And that’s it, our tweet is sent!