Automation Posting tweet into twitter by python/selenium

Python
この記事は約4分で読めます。

This time, it is completely one of my hobby, I made a function to automatically post to twitter using selenium.

Advertisements

Preparation

  • pip environment
  • selenium(install into pip)
  • python3

what implement by python/selenium

  1. Log-in your own twitter account
  2. Posting text by setting in python code
  3. automating script fired by cron/launched

Gaol of real tweet in twitter

As a result of actual execution, can login and tweet is completed.

Actual Code by python

import time, sys
from selenium import webdriver as wd
from selenium.webdriver.common.keys import Keys
from requests import request as rq
from selenium.webdriver import Chrome, ChromeOptions
import chromedriver_binary


options = ChromeOptions()
#options.add_argument('-headless')

driver = wd.Chrome()
url = "https://twitter.com/"

driver.get(url)


driver.find_element_by_xpath('//*[@id="doc"]/div/div[1]/div[1]/div[2]/div[2]/div/a[2]').click()

time.sleep(3)
id = driver.find_element_by_xpath('//*[@id="page-container"]/div/div[1]/form/fieldset/div[1]/input')
id.send_keys("input your own Twitter Account Name")

password = driver.find_element_by_xpath('//*[@id="page-container"]/div/div[1]/form/fieldset/div[2]/input')
password.send_keys('input your own Twitter Account Password for login')

driver.find_element_by_xpath('//*[@id="page-container"]/div/div[1]/form/div[2]/button').click()

try:
    time.sleep(2)
    elem = driver.find_element_by_xpath('//*[@id="tweet-box-home-timeline"]')
    elem.send_keys("input text you want to tweet: test from selenium")
    print("input_done")
    time.sleep(2)
    elem.send_keys(Keys.CONTROL, Keys.ENTER)

except KeyboardInterrupt:
    print("nprogram was ended.n")
    sys.exit()

Setting Launched in mac

please refer to following articles about how to set up Launched on your local MAC.

(Sorry, at this moment, the article is only written by Japanese. in the future, i will also translate it from ja to en)

Finally,

Honestly it is possible to use Twitter API, but since a while after using selenium by a request from an acquaintance, I made an automatic posting function to Twitter by python/selenium.

Have a nice automation days!

コメント