Using Python and Selenium to Tweet

Setting up

  • Python
$ 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.>>>
  • Selenium
>>> from selenium import webdriver
$ pip install selenium
  • Webdriver

Writing your Python file

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
url = 'https://twitter.com/login'
userUsername = 'yourTwitterUsername'
userPassword = 'your password'
def main():
browser = webdriver.Chrome('/Users/rmiriuk/chromedriver')
browser.get(url)
$ Python twitterBot.py

Finding the lost input field

browser.implicitly_wait(5)
user = browser.find_element_by_name('session[username_or_email]')
user.send_keys(userUsername)
password = browser.find_element_by_name('session[password]')
password.send_keys(userPassword)
password.send_keys(Keys.ENTER)

Sending a 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')
button = browser.find_element_by_css_selector("div[data-testid='tweetButtonInline']")
button.click()
browser.close()

Conclusion

--

--

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