mecobalamin’s diary

人間万事塞翁が馬

https://help.hatenablog.com/entry/developer-option

Pythonでtweetを収集する

~~~追記~~~
2021/12/18 6:46
エラーが出て動かない
久々に使ったのでいつからエラーが出るようになったか不明

twint.token.RefreshTokenException: Could not find the Guest token in HTML

原因を調べてわかったら記事を書き直します。
~~~追記ここまで~~~

~~~追記その2~~~
2022/05/19 8:12
twintの開発が止まっているようです
self-development.info

別の方法を考えます
~~~追記その2ここまで~~~

Pythonを使ってtweetを収集する

twintを使う
twint · PyPI

インストール

$ pip3 install twint

twintはコマンドラインpythonスクリプトの両方から使える

例えば@usernameのツイートから
Donald Trunpに関係するツイートを収集して
json形式のファイルに保存する

コマンドラインからは以下のようにする

$ twint -u username -s "Donald Trump"  -o file.json --json

pythonスクリプトの場合はこんな感じ

import twint, json

path_json = 'c:\\path\\to\\json\\file.json'

with open(path_json, 'w'):
    pass

c = twint.Config()
c.Username = "username"
c.Search = "Donald Trump"
c.Hide_output = True
c.Store_json = True
c.Output = path_json

twint.run.Search(c)

json_dict = []
with open(path_json, 'r', encoding = 'utf-8') as f:
    for line in f:
        json_dict.append(json.loads(line))

あとは出力されたjsonファイルを
煮るなり焼くなり好きに処理する

実行時に
>
CRITICAL:root:twint.get:User:'NoneType' object is not subscriptable + Unicode<
といったエラーが出る場合は
twintをインストールし直す
CRITICAL:root:twint.get:User:'NoneType' object is not subscriptable + Unicode issues · Issue #384 · twintproject/twint · GitHub

pip3 install --upgrade -e git+https://github.com/twintproject/twint.git@origin/master#egg=twint

あと、Jsonファイルはcp932でエンコードされているが
pythonで読み込むとエラーになる
それでencodingにutf-8を指定している

windowsだとこういう方法もある
【Windows】PythonでCP932(Shift-JIS)エンコード以外のファイルを開くとエラーになる問題がとりあえずの解決に至った件 - Qiita