Twitter Automation using Selenium Python
Last Updated :
19 Apr, 2023
If you are someone like me who considers Twitter to be far better than Instagram, then I might be having something for you. We all know gaining followers on twitter can be pretty tough but sometimes retweeting quality content can gain you, followers, too. Obviously, you are a busy person and you don't have time to sit around on your phone or laptop to read and retweet content. Pretty boring task right? Let's make our smart friend do it. This article revolves around how to automate twitter using selenium Python.
First, you will be needing Python. You download python from here. Now, let's begin coding. First, create a folder named Twitter Automation and then change the directory to the newly created folder. Now, create a file named requirements.txt and add just this one line to it.
selenium==3.141.0
Next, open up your terminal and type
pip install -r requirements.txt
Next, you will need a chrome driver. You can download it from here. After the download is complete, move the downloaded driver to your newly created folder Twitter Automation.
Now all the requirements are taken care of. Now let's begin with the coding.
Now, create a file called credentials.txt and add the following lines to it.
email: {your twitter email}
password: {your twitter password}
Replace the email and password placeholder with your original credentials of twitter. I am using a text file. One could also use a .env file but here for simplicity I am using a .txt file.
Next, create another file called secrets.py and add the following lines of code to it.
Python3
"""
Add your twitter handle's email and password
in the credentials.txt file.
This will be used to automate the login.
"""
def get_credentials() -> dict:
# dictionary for storing credentials
credentials = dict()
# reading the text file
# for credentials
with open('credentials.txt') as f:
# iterating over the lines
for line in f.readlines():
try:
# fetching email and password
key, value = line.split(": ")
except ValueError:
# raises error when email and password not supplied
print('Add your email and password in credentials file')
exit(0)
# removing trailing
# white space and new line
credentials[key] = value.rstrip(" \n")
# returning the dictionary containing the credentials
return credentials
I have added a detailed code explanation in the inline comments for better understanding. Now, let's create the most important file, the one which does all the magic. Create a new file called twitterbot.py and add the following lines to it.
Python3
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
'''Uncomment the below line when running in linux'''
# from pyvirtualdisplay import Display
import time, os
class Twitterbot:
def __init__(self, email, password):
"""Constructor
Arguments:
email {string} -- registered twitter email
password {string} -- password for the twitter account
"""
self.email = email
self.password = password
# initializing chrome options
chrome_options = Options()
# adding the path to the chrome driver and
# integrating chrome_options with the bot
self.bot = webdriver.Chrome(
executable_path = os.path.join(os.getcwd(), 'chromedriver'),
options = chrome_options
)
def login(self):
"""
Method for signing in the user
with the provided email and password.
"""
bot = self.bot
# fetches the login page
bot.get('https://twitter.com / login')
# adjust the sleep time according to your internet speed
time.sleep(3)
email = bot.find_element_by_xpath(
'//*[@id ="react-root"]/div / div / div[2]/main / div / div / form / div / div[1]/label / div / div[2]/div / input'
)
password = bot.find_element_by_xpath(
'//*[@id ="react-root"]/div / div / div[2]/main / div / div / form / div / div[2]/label / div / div[2]/div / input'
)
# sends the email to the email input
email.send_keys(self.email)
# sends the password to the password input
password.send_keys(self.password)
# executes RETURN key action
password.send_keys(Keys.RETURN)
time.sleep(2)
def like_retweet(self, hashtag):
"""
This function automatically retrieves
the tweets and then likes and retweets them
Arguments:
hashtag {string} -- twitter hashtag
"""
bot = self.bot
# fetches the latest tweets with the provided hashtag
bot.get(
'https://twitter.com / search?q =% 23' + \
hashtag+'&src = typed_query&f = live'
)
time.sleep(3)
# using set so that only unique links
# are present and to avoid unnecessary repetition
links = set()
# obtaining the links of the tweets
for _ in range(100):
# executing javascript code
# to scroll the webpage
bot.execute_script(
'window.scrollTo(0, document.body.scrollHeight)'
)
time.sleep(4)
# using list comprehension
# for adding all the tweets link to the set
# this particular piece of code might
# look very complicated but the only reason
# I opted for list comprehension because is
# lot faster than traditional loops
[
links.add(elem.get_attribute('href'))\
for elem in bot.find_elements_by_xpath("//a[@dir ='auto']")
]
# traversing through the generated links
for link in links:
# opens individual links
bot.get(link)
time.sleep(4)
try:
# retweet button selector
bot.find_element_by_css_selector(
'.css-18t94o4[data-testid ="retweet"]'
).click()
# initializes action chain
actions = ActionChains(bot)
# sends RETURN key to retweet without comment
actions.send_keys(Keys.RETURN).perform()
# like button selector
bot.find_element_by_css_selector(
'.css-18t94o4[data-testid ="like"]'
).click()
# adding higher sleep time to avoid
# getting detected as bot by twitter
time.sleep(10)
except:
time.sleep(2)
# fetches the main homepage
bot.get('https://twitter.com/')
Now, it's time to code our driver script. To do that, create a file called main.py and add the following lines to it.
Python3
import twitterbot as tb
import secrets, sys
# fetches the hashtag from command line argument
hashtag = sys.argv[1]
# fetches the credentials dictionary
# using get_credentials function
credentials = secrets.get_credentials()
# initialize the bot with your credentials
bot = tb.Twitterbot(credentials['email'], credentials['password'])
# logging in
bot.login()
# calling like_retweet function
bot.like_retweet(hashtag)
Now, we are done with the code. Let's call our driver script by running the following command in your terminal.
python main.py {hashtag}
Just in place of the hashtag placeholder replace it with any trending hashtag, for example, you can try
python main.py python3
This will like and retweet 100 tweets with the hashtag python. You can check out how it would perform in the video below. So, there you have it. Go ahead and try it out and do not increase the number of tweets because twitter has a daily limit of tweets.
Some advantages of using Selenium for Twitter automation include:
- Improved productivity: Automation allows you to perform tasks faster and more efficiently, freeing up time for other tasks.
- Consistency: Automation ensures that tasks are performed consistently and accurately, reducing the risk of errors.
- Customizability: Selenium allows you to customize the automation to meet your specific requirements.
Some disadvantages of using Selenium for Twitter automation include:
- Limited capabilities: Selenium can only automate tasks that are available through the web interface, so it may not be suitable for tasks that require more advanced functionality.
- Maintenance: Automation scripts may require regular maintenance to keep up with changes in the Twitter interface and API.
- Risk of account suspension: Twitter has strict rules against automation, so it's important to use automation responsibly and within the limits set by Twitter to avoid account suspension or banning.
Similar Reads
Browser Automation Using Selenium Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Mastering Selenium will help you automate your day to da
3 min read
Retweet Tweet using Selenium in Python Prerequisites : Selenium Webdriver.Web Driver MethodsWays to locate elements in a webpage In this article, we are going to see how to retweets for a particular hashtag and decide on whether it will be displayed in the Trending Section of Twitter or not. We can automate an account on Twitter into ret
4 min read
Get all text of the page using Selenium in Python As we know Selenium is an automation tool through which we can automate browsers by writing some lines of code. It is compatible with all browsers, Operating systems, and also its program can be written in any programming language such as Python, Java, and many more. Selenium provides a convenient A
3 min read
Interacting with Webpage - Selenium Python Seleniumâs Python module is designed for automating web testing tasks in Python. It provides a straightforward API through Selenium WebDriver, allowing you to write functional and acceptance tests. To open a webpage, you can use the get() method for navigation. However, the true power of Selenium li
4 min read
Writing Tests using Selenium Python Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This art
2 min read
How to get text of a tag in selenium - Python? Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. In this article, we will w
1 min read
Navigating links using get method - Selenium Python Selenium's Python module allows you to automate web testing using Python. The Selenium Python bindings provide a straightforward API to write functional and acceptance tests with Selenium WebDriver. Through this API, you can easily access all WebDriver features in a user-friendly way. This article e
2 min read
Non blocking wait in selenium using Python Prerequisite : Browser Automation Using SeleniumWhen we want to do web automation, we require to wait for some javascript elements to load before we perform some action. For that matter, generally people use Python3 time.sleep(in_seconds) which is a blocking call.By blocking call I mean, it waits or
3 min read
Selenium Python Tutorial Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python , Java , C# , etc, we will be working with Python. Selenium Tutorial cover
9 min read
Python | Automating Happy Birthday post on Facebook using Selenium As we know Selenium is a tool used for controlling web browsers through a program. It can be used in all browsers, OS, and its program are written in various programming languages i.e Java, Python (all versions). Selenium helps us automate any kind of task that we frequently do on our laptops, PCs
3 min read