Using Python and Selenium to Tweet

How to write a python project that uses Selenium and Webdriver to login to your Twitter and post something without using Twitter API.

You can find the code for this project on my GitHub.

This tutorial is made on a Mac if you are using a Windows or a Linux it might be a little different for you.

Setting up

For this tutorial you will need to have installed in your machine:

  • Python

To check if you have Python installed on your machine, open the terminal and write “python” on the command line.

$ pythonPython 3.7.6 (default, Jan  8 2020, 13:42:34)[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwinType "help", "copyright", "credits" or "license" for more information.>>>

If you have it installed it should open the python console like the one above, to exit it, type “exit()” and then “enter”

  • Selenium

The easiest way of checking if you have selenium installed is to open the python console again and type:

>>> from selenium import webdriver

If you don’t have any errors it means it’s installed, in case you don’t, just type this on your terminal (after leaving python console):

$ pip install selenium

Note: never believe what people tell you to write on your terminal, go to the source and check if that is right, as far as you know, I could be installing something malicious on your machine.

source: https://selenium-python.readthedocs.io/installation.html

  • Webdriver

The web driver will depend on what is your browser of choice, I use Chrome and to install the driver I needed to know what version I was using, to check yours follow this link.

then, download the driver on this page.

If you want to instal for Mozilla this link.

You will need to save the file somewhere you know how to find, as we will need to know the path.

Writing your Python file

Create a new python file, I have called my twitterBot.py, and the first thing you need to do is import selenium to your file, we will also need to access the keys on our keyboard, so we should be importing those too.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

I also imported WebDriverWait and we will see why later.

Now let’s set our variables, I prefer to organize all my variables in one place, especially in a small project like this

url = 'https://twitter.com/login'
userUsername = 'yourTwitterUsername'
userPassword = 'your password'

Now let’s create our main function and the first thing we will do is to get our browser and open our URL.

def main():
browser = webdriver.Chrome('/Users/rmiriuk/chromedriver')
browser.get(url)

Remember when I mentioned you need to know where your driver was? It’s because you need to pass the path as an argument, some people might be able to not declare anything, simply type “ browser = webdriver.Chrome()” and it works fine.

You then later is asking the browser to open the URL declared above.

If you got to your terminal and run the file, it should open on the twitter login page.

$ Python twitterBot.py

Nice, now the easy part is done.

Finding the lost input field

Now that you opened the browser we the fun stuff begins.

We have now access to a really fun tool from selenium, where we can “find elements” in the page, you can check all the locating elements in this link here, as I won’t go too deep in detail.

But to be able to find the elements in the page, it needs to be loaded before we start looking for them, so add the following code after get.(url):

browser.implicitly_wait(5)

It will ask the browser to wait for 5 seconds before trying to do anything.

We need now to “find” where the user types the username, the easiest way is to inspect the HTML of the page and get the id or a class, but twitter made it a little bit trickier than that, it took me a couple of trial and errors.

But in the end, I managed to “find” it by find the name

user = browser.find_element_by_name('session[username_or_email]')

Cool, now we can use use_keys to pass our username and see it written on the input field.

user.send_keys(userUsername)

Now, we can do the same with the password, and while we are there, we can also “press the key enter” so we login on the page.

password = browser.find_element_by_name('session[password]')
password.send_keys(userPassword)
password.send_keys(Keys.ENTER)

If you run the app you should be able to log in.

Sending a message

Now we are inside, we will try to find the field where the user type their tweet and do like we did on username and password.

If you want to do by yourself this time, I can wait.

In here we also need to wait until the page is loaded before trying to find an element, and it was also needed to use another way to locate the element, I used find_element_by_css_selector, and I already gave it my message.

browser.implicitly_wait(5)
tweet = browser.find_element_by_css_selector("br[data-text='true']")
tweet.send_keys('I am a bot, bep bop')

Cool, if you run your code, your message should appear in the text field.

Now the last thing is to click on the tweet button, to publish what you wrote.

First, we find it as we have done before, inspecting the HTML file and finding the element:

button = browser.find_element_by_css_selector("div[data-testid='tweetButtonInline']")

And now that we have a button, we can literally click on it:

button.click()

And there is your tweet! Congratulations!

I would also advise you to close it before exiting:

browser.close()

Conclusion

Your code should look like this:

--

--

--

Interested in everything, writing about tech

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Run Batch Job In Container: Azure Container Instances

Handlin Object Types

Query Azure Data Lake via Synapse Serverless Security Credentials Setup

How To Tell an Employee They Are Not Ready For a Promotion

If you have this three things, you can be a programmer too.

Person look at computer with hands on keyboard

Get started with Sitecore Experience Edge For XM — Part 3

Business Software and Power Tools

SRE: Building a Culture of Reliability, Resiliency and Risk Management

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Renata Miriuk

Renata Miriuk

Interested in everything, writing about tech

More from Medium

Reading the latest WhatsApp messages with python

QR Codes with Python

A Simple Guide to Learn Python for Beginner — Chapter 1: Installation

Creating a Personal Diary using Python and Django