I wanted to make a twitter bot, so I did a lot of research. Since it is troublesome to get the twitter API, we aim to automatically tweet by selenium.
-Selenium Official -[[Python] Try automating Twitter using Selenium. ](Https://mahimahironron.hateblo.jp/entry/2020/04/01/%E3%80%90Python%E3%80%91Selenium%E3%82%92%E4%BD%BF%E3%81%A3 % E3% 81% A6Twitter% E3% 82% 92% E8% 87% AA% E5% 8B% 95% E5% 8C% 96% E3% 81% 97% E3% 81% A6% E3% 81% BF% E3 % 82% 8B% E3% 80% 82)
Just write and execute a script like the one below. Please rewrite your account and password as appropriate.
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
#account information
account = 'xxxxxxxxxxx'
password = 'xxxxxxxxxxx'
#The string you want to tweet
text = "Test tweet"
#Twitter login process to execute
def login_twitter():
#Open login page
driver.get('https://twitter.com/login/')
time.sleep(2) #Wait
#account input
element_account = driver.find_element_by_name("session[username_or_email]")
element_account.send_keys(account)
time.sleep(2) #Wait
#Enter password
element_pass = driver.find_element_by_name("session[password]")
element_pass.send_keys(password)
time.sleep(3) #Stop working
#Click login button
element_login = driver.find_element_by_xpath('//*[@data-testid="LoginForm_Login_Button"]')
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
element_login.click()
time.sleep(3) #Wait
def send_tweet(text):
element_text = driver.find_element_by_class_name("notranslate")
element_text.click()
element_text.send_keys(text)
tweet_button = driver.find_element_by_xpath('//*[@data-testid="tweetButtonInline"]')
tweet_button.click()
#Start selenium
options=Options()
driver=webdriver.Chrome(chrome_options = options)
#Login process
login_twitter()
#Tweet
send_tweet(text)
time.sleep(10)
#Exit selenium
driver.close()
driver.quit()
Recommended Posts