pythonを用いたtwitterスクレイピングについて
Q&A
Closed
Pythonを使ってtwitterテキストマイニングをするため、スクレイピングをしようとしています。書籍「python最速データ収集術」を参考にしながらコードを書こうとしているのですが、エラーが発生しました。解決方法を教えてください。
基本的な環境
Python3とanacondaとjupyterを使用
Twitter APIのAcademic取得済み
OAuth認証済み
Conda とdateutilとpytzをインストール済み
以下のコードは「イーロンマスク」の単語を含むツイートについて50個取得しようとしたもの
入力1:
import json
from requests_oauthlib import OAuth1Session
from dateutil import parser
from pytz import timezone
import datetime
import csv
入力2:
API_KEY = "自分のAPIキー"
API_SECRET_KEY = "自分のAPIシークレットキー"
ACCESS_TOKEN = "自分のアクセストークン"
ACCESS_TOKEN_SECRET = "自分のアクセストークンシークレット"
#Twitter APIの利用申請時に確認したキーとトークンを設定
入力3:
tweet_count = 50 #Standard sarch APIのパラメーターの内、必要なものを変数に設定
result_type = "recent"
search_keyword = "イーロンマスク"
params = {"count": tweet_count,"result_type":result_type,"q":search_keyword} #キーと値(ここでは変数に格納)を元に全てのパラメーターを辞書型で変数paramsに格納
入力4:
url = " https://api.twitter.com/2/tweets "
twitter = OAuth1Session(API_KEY,API_SECRET_KEY,ACCESS_TOKEN,ACCESS_TOKEN_SECRET) #キーとトークンを元にAPIに接続
response = twitter.get(url, params=params) #URLとパラメーターを元に検索結果を取得
twitter_data = json.loads(response.text)
入力5:
twitter_data
出力:
JSONDecodeError Traceback (most recent call last)
Cell In[4], line 5
3 twitter = OAuth1Session(API_KEY,API_SECRET_KEY,ACCESS_TOKEN,ACCESS_TOKEN_SECRET) #キーとトークンを元にAPIに接続
4 response = twitter.get(url, params=params) #URLとパラメーターを元に検索結果を取得
----> 5 twitter_data = json.loads(response.text)
File ~\anaconda3\lib\json_init_.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
341 s = s.decode(detect_encoding(s), 'surrogatepass')
343 if (cls is None and object_hook is None and
344 parse_int is None and parse_float is None and
345 parse_constant is None and object_pairs_hook is None and not kw):
--> 346 return _default_decoder.decode(s)
347 if cls is None:
348 cls = JSONDecoder
File ~\anaconda3\lib\json\decoder.py:337, in JSONDecoder.decode(self, s, _w)
332 def decode(self, s, _w=WHITESPACE.match):
333 """Return the Python representation of s
(a str
instance
334 containing a JSON document).
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):
File ~\anaconda3\lib\json\decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
最初は出力5を実行すると
{'errors': [{'parameters': {'ids': []},
'message': 'The ids
query parameter can not be empty'},
{'parameters': {'count': ['5']},
'message': 'The query parameter [count] is not one of [ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]'},
{'parameters': {'result_type': ['recent']},
'message': 'The query parameter [result_type] is not one of [ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]'},
{'parameters': {'q': ['イーロンマスク']},
'message': 'The query parameter [q] is not one of [ids,expansions,tweet.fields,media.fields,poll.fields,place.fields,user.fields]'}],
'title': 'Invalid Request',
'detail': 'One or more parameters to your request was invalid.',
'type': 'https://api.twitter.com/2/problems/invalid-request'}
のエラーが出ていましたが、しばらく経ってから同様の実行をすると出力4の段階で上記の「出力:」のようなエラーが出ました。卒業論文を書くため、プログラミング初心者として試行錯誤を続けているのですが、行き詰まって困り果てています。どなたか助けていただけると幸いです。よろしくお願いします。