Skip to content

Instantly share code, notes, and snippets.

@pranshuj73
Last active April 26, 2020 00:03
Show Gist options
  • Save pranshuj73/29db8957901ad8c06700db8d0beafc0f to your computer and use it in GitHub Desktop.
Save pranshuj73/29db8957901ad8c06700db8d0beafc0f to your computer and use it in GitHub Desktop.
Final Version of Selenium Twitter Bot
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
class Tweeter:
@classmethod
def login(self):
username = "your username/email will go here"
password = "and your password shall go here"
# opens up the browser window
self.driver = webdriver.Chrome()
driver = self.driver
# loads twitter login page for us
driver.get("https://twitter.com/login")
#sleeps for awhile to let page load
sleep(3)
# everything here is a part of login function of Tweeter class
# Now we need to find the field where we want to type in the username/email
uname_field = driver.find_element_by_name("session[username_or_email]")
# typing the username
# Note: it's important to press tab using Keys.TAB after typing the username
# to switch to the password field (or we can add extra lines of code to click on it)
uname_field.send_keys(username, Keys.TAB)
# selecting the password field
pass_field = driver.find_element_by_name("session[password]")
# typing the password and pressing enter key using Keys.RETURN to submit everything
pass_field.send_keys(password, Keys.RETURN)
# This function is a part of Tweeter class which will allow us to tweet
@classmethod
def tweet(self):
tweet_text = input("Enter your tweet here: ")
driver = self.driver
sleep(3)
# finds the compose tweet button
tweet_btn = driver.find_element_by_xpath("//a[@aria-label=\"Tweet\"]")
tweet_btn.click()
sleep(2)
# This will type text in the text field
tweet_field = driver.find_element_by_xpath("//div[@aria-label=\"Tweet text\"]")
tweet_field .click()
sleep(1)
tweet_field.send_keys(tweet_text)
# sends the tweet
tweetbtn = driver.find_element_by_xpath("//*[contains(text(),'Tweet')]")
tweetbtn.click()
sleep(1)
# success message
print("Your tweet has been tweeted!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment