こんにちは、ミナピピン(@python_mllover)です
久しぶりにTwitterに自動ログインする必要があったので昔に書いたコードを実行したところ案の定HTML要素が変わっていてエラーを吐いたので2021年版として書き直しました。
なにか質問等あれば、MENTA Twitterにてご相談ください。
# ライブラリの読み込み
import time
import subprocess
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import chromedriver_binary
cmd = 'pip install --upgrade chromedriver_binary'
res = subprocess.call(cmd, shell=True)
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications" : 2}
chrome_options.add_experimental_option("prefs",prefs)
# chrome_options.add_argument('--headless')
drv = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
# ツイッターに自動投稿する関数
def auto_tweet(id, password, tweet):
"""[twitterに自動投稿するスクリプト]
id : str
自分のツイッターのID
password : str
自分のツイッターのパスワード
tweet : str
投稿したいツイート
"""
global drv
drv.get('https://twitter.com/login/')
time.sleep(10)
drv.find_element_by_xpath(
'/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input')\
.send_keys(id)
time.sleep(2)
drv.find_element_by_xpath('/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[6]/div')\
.click()
time.sleep(2)
drv.find_element_by_xpath(
'/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[3]/div/label/div/div[2]/div[1]/input')\
.send_keys(password)
time.sleep(2)
drv.find_element_by_xpath(
'/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[2]/div/div/div').click()
time.sleep(2)
drv.get('https://twitter.com/compose/tweet')
time.sleep(4)
drv.find_element_by_css_selector(
'.notranslate.public-DraftEditor-content').send_keys(tweet)
time.sleep(3)
drv.find_element_by_xpath(
'/html/body/div/div/div/div[1]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div[3]/div/div/div/div[1]/div/div/div/div/div[2]/div[3]/div/div/div[2]/div[4]/div/span/span').click()
drv.quit()
# ツイートを投稿する例
auto_tweet('@xxxxxx', 'hogehoge', 'helloworld selenium2021')

コメント
[…] 関連記事:【2021年版】Python+Seleniumでツイッターに自動でログインしてツイートする […]
[…] 参考:【2021年版】Python+Seleniumでツイッターに自動でログインしてツイートする […]