LoginSignup
1
4

More than 3 years have passed since last update.

Python+seleniumを使ってtwitterにログインし、特定ユーザのツイートを抜き出す方法

Last updated at Posted at 2019-10-14

Pythonを利用してtwitterにログインし、特定ユーザのツイートを抜き出すプログラムを書こうとしています。(下記のプログラムではツイートIDの抜き出しまで)
しかし、下記のプログラムを動かしてもツイートIDがcsvファイルに吐き出されません。
空のcsvファイルができます。

「ログインボタン要素の取得」と「ログインボタンを押下」のコマンド部分をコメントアウトするとなぜかcsvファイルの中にツイートIDが入るようになるのですが、なぜこのような動作になるのか理解できず困っています。
原因に心当たりの方がおられましたら、アドバイスいただけると助かります。
※最終的にtwitterの鍵垢の人のツイートを保存したいので、twitterへのログインは必須だと考えています。

動作環境

Windows10
Python 3.7.4

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
from time import sleep

driver=webdriver.Chrome("./driver/chromedriver.exe")

# 各種設定
# twitterアカウント
user_id = 'xxxxxxxxxx@test.com'
password = 'xxxxxxxxxx'

# ログインページを開く
driver.get('https://twitter.com/login/')
time.sleep(3)  # 動作止める

#ユーザーid入力フォーム要素の取得
user_box = driver.find_element_by_class_name('js-username-field')
#取得した要素へidを入力
user_box.send_keys(user_id)
sleep(1)
#パスワード入力フォーム要素の取得
password_box = driver.find_element_by_class_name('js-password-field')
#取得した要素へキー入力
password_box.send_keys(password)
sleep(1)
#ログインボタン要素の取得
login_btn = driver.find_element_by_css_selector('button.submit.EdgeButton.EdgeButton--primary.EdgeButtom--medium')
#ログインボタンを押下
login_btn.click()
sleep(1)

driver.get('https://twitter.com/TwitterJP')
soup = driver.page_source
text = BeautifulSoup(soup,'html.parser')

#IDを抜く部分
_id_list = []
for tweet in text.select("div.tweet"):
        _id_list.append(tweet['data-tweet-id'])
#リツイートによる重複を無くす
new_list = list(set(_id_list))


#ファイルに書き込み
f = open ('test_id.txt','a',encoding='utf-8')

for tweet in new_list:
        f.write(tweet+'\n')
f.close()
1
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4