Seleniumからツイートする(2023/02/08時点)

要素取得の大部分でXPATHを利用しているのと、TwitterのHTMLが変わりやすいので注意してください。

# ちょっと待つためのtime
import time
# webdriver・Options・By・fsをseleniumからインポート
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome import service as fs

# detachオプションを指定して、chromedriverが勝手に落ちないようにする
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)

# アカウント情報
accountID = 'TwitterのIDを入力'
password = 'パスワードを入力'

# ツイートしたい文字列
tweet = "あいうえお"


# seleniumを起動
service = fs.Service("chromedriverのパスを入力")
driver = webdriver.Chrome(service=service, options=chrome_options)

def twitterLogin(account,password):
    driver.get('https://twitter.com/login/')
    time.sleep(3)

    # IDを入力する
    idInput = driver.find_element(By.TAG_NAME,"input")
    idInput.send_keys(account)
    time.sleep(5)
    # 次へボタンクリック
    element_login = driver.find_element(By.XPATH,"/html/body/div/div/div/div[1]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[6]")
    element_login.click()
    time.sleep(5) 

    # パスワードを入力する
    passInput = driver.find_element(By.XPATH,"/html/body/div/div/div/div[1]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div/div[3]/div/label/div/div[2]/div[1]/input")
    passInput.send_keys(password)
    time.sleep(5)

    # 次へボタンクリック
    element_login = driver.find_element(By.XPATH,"/html/body/div/div/div/div[1]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[2]/div/div[1]/div/div/div")
    element_login.click()
    time.sleep(5) 


def tweet_submit(text):
    # テキストボックスを表示
    element_tweet_button = driver.find_element(By.XPATH, '//*[@id="react-root"]/div/div/div[2]/header/div/div/div/div[1]/div[3]/a')
    element_tweet_button.click()
    time.sleep(5)

    # テキストを入力
    element_tweet_textbox = driver.find_element(By.CLASS_NAME,"notranslate.public-DraftEditor-content")
    element_tweet_textbox.send_keys(text)
    time.sleep(5)

    # ツイートボタンをクリック
    element_tweet_submit = driver.find_element(By.XPATH, '//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div/div[3]/div[2]/div[1]/div/div/div/div/div[2]/div[3]/div/div/div[2]/div[4]')
    element_tweet_submit.click()
    
    driver.close()
    
twitterLogin(accountID,password)
tweet_submit(tweet)

コメント

タイトルとURLをコピーしました