Skip to content
Related Articles

Related Articles

Improve Article

Retweet Tweet using Selenium in Python

  • Difficulty Level : Medium
  • Last Updated : 11 Aug, 2021

Prerequisites :

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 retweeting all the tweets related to any particular hashtag. This can be achieved using Selenium in Python.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Note: You can get webdriver downloaded from here.



Stepwise implementation:

Step 1: Import the required modules

Python3




from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass

 
 

Step 2 Execute the webdriver and assign it to a variable driver.

Python3




driver = webdriver.Chrome(executable_path='/usr/lib/chromium-browser/chromedriver')

 
 

Step 3: Direct to the required URL and maximize the window using maximize_window.

Python3






driver.maximize_window()

 
 

Step 4: Ask the user for the Twitter account credentials and send them to the username and password input box by locating them through their paths. Use the getpass in order to input passwords for better security. You can insert the credentials at the required locations send_keys() .

Python3




username = input('Enter Your Username: ')
password = getpass.getpass(prompt = 'Enter Your Password: ')
 
# locating the input box for username
u = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div[2]/form/div/div[1]/label/div/div[2]/div/input')
u.send_keys(''+str(username)+'')
 
# locating the input box for password
p = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]/\
main/div/div/div[2]/form/div/div[2]/label/div/div[2]/div/input')
p.send_keys(''+str(password)+'')

 
 

Step 5: Locate the log-in button through XPath and click on it click(). Also, wait for the webpage to load using the same methods previously used.

Python3




driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div[2]/form/div/div[3]/div').click()
time.sleep(10)

 
 

Step 6. Ask the user for the hashtag to be retweeted and insert it into the search box using the xpath and send_keys() as done previously.

Python3




srch = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div\
/form/div[1]/div/label/div[2]/div/input')
 
s = input('Enter the Hashtag you want to retweet: ')
srch.send_keys('#'+str(s)+'')
srch.send_keys(Keys.ENTER)

 
 



Step 7: Ask for the maximum number of retweets the user wants to do and direct to the latest tweets section using xpath. Also, wait for the webpage to load using time.sleep().

Python3




c = int(input('Max no. of Retweets: '))
driver.implicitly_wait(5)
driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div/div[1]/div/div[1]/div[2]/nav/div/div[2]/div/div[2]/a').click()
time.sleep(10)

Step 8: Initiate a while loop that breaks when the max number of retweets is achieved. Inside the loop, locate all the retweet buttons (using previous methods) and click on them one by one. 

Python3




while(1):
   
      # waiting for the webpage to load
    time.sleep(5)
    rt=driver.find_elements_by_css_selector('.css-18t94o4[data-testid ="retweet"]')
    for r in rt:
        try:
            r.click()
            time.sleep(2)
            driver.find_element_by_xpath('//*[@id="layers"]\
            /div[2]/div/div/div/div[2]/div[3]/div/div/div/div').click()
             
            c -= 1
            time.sleep(2)
            if(c == 0):
                break
        except (ElementClickInterceptedException, StaleElementReferenceException):
            pass
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
    if(c == 0):
        break

Below is the full implementation:

Python3




from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass
 
# initializing the driver
driver = webdriver.Chrome(
  executable_path='/usr/lib/chromium-browser/chromedriver')
 
# directing to the twitter login page
driver.maximize_window()
 
# asking the user for username and pas
username = input('Enter Your Username: ')
password = getpass.getpass(prompt='Enter Your Password: ')
 
# locating the input box for username
u = driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[1]\
/label/div/div[2]/div/input')
 
# inputing the username
u.send_keys(''+str(username)+'')
 
# locating the input box for password
p = driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[2]\
/label/div/div[2]/div/input')
 
# inputing the password
p.send_keys(''+str(password)+'')
print("loading... \n")
time.sleep(3)
 
# logging in
driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[3]/div').click()
time.sleep(10)
 
# Locating the search box
srch=driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div/div[2]/div/div[2]\
/div/div/div/div[1]/div/div/div/form/div[1]\
/div/label/div[2]/div/input')
 
# inputing the hashtag to retweet
s = input('Enter the Hashtag you want to retweet: ')
 
# inputing the hashtag
srch.send_keys('#'+str(s)+'')
 
# searching for the hashtag
srch.send_keys(Keys.ENTER)
 
# inputing maximum number of tweets one wants to retweet
c=int(input('Max no. of Retweets: '))
driver.implicitly_wait(5)
 
# directing the most latest tweets
driver.find_element_by_xpath('//*[@id="react-root"]/div/\
div/div[2]/main/div/div/div/div[1]/div/div[1]/div[2]/\
nav/div/div[2]/div/div[2]/a').click()
time.sleep(10)
 
 
while(1):
    time.sleep(5)
     
    # locating the retweet option in the webpage
    rt = driver.find_elements_by_css_selector(
      '.css-18t94o4[data-testid ="retweet"]')
    for r in rt:
        try:
               
            # retweeting
            r.click()
            time.sleep(2)
             
            # toggling the confirmation to retweet
            driver.find_element_by_xpath('//*[@id="layers"]/div[2]\
            /div/div/div/div[2]/div[3]/div/div/div/div').click()
            c -= 1
            time.sleep(2)
            if(c==0):
                break # breaking from the retweet loop
        except (ElementClickInterceptedException, StaleElementReferenceException):
            pass
           
     # scrolling to the bottom of the page
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
     
     # max number of retweets are achieved
    if(c==0):
        break # breaking from the retweet loop
driver.close()

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :