forked from sashaperigo/Trump-Tweets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrump_tweets.py
217 lines (182 loc) · 7.62 KB
/
trump_tweets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""A script used to download all of Donald Trump's public tweets.
Adapted from Tom Dickinson's repository:
https://github.com/tomkdickinson/Twitter-Search-API-Python
"""
import urllib2
import csv
import json
import datetime
from abc import ABCMeta
from urllib import urlencode
from abc import abstractmethod
from urlparse import urlunparse
from bs4 import BeautifulSoup
from time import sleep
__author__ = 'Tom Dickinson'
OUT_FILE = "/Users/sashaperigo/Desktop/trump_tweets.csv"
class TwitterSearch:
__metaclass__ = ABCMeta
def __init__(self, rate_delay, error_delay=5):
"""
:param rate_delay: How long to pause between calls to Twitter
:param error_delay: How long to pause when an error occurs
"""
self.rate_delay = rate_delay
self.error_delay = error_delay
def search(self, query):
"""
Scrape items from twitter
:param query: Query to search Twitter with. Takes form of queries constructed with using Twitters
advanced search: https://twitter.com/search-advanced
"""
url = self.construct_url(query)
continue_search = True
min_tweet = None
response = self.execute_search(url)
while response is not None and continue_search and response['items_html'] is not None:
tweets = self.parse_tweets(response['items_html'])
# If we have no tweets, then we can break the loop early
if len(tweets) == 0:
break
# If we haven't set our min tweet yet, set it now
if min_tweet is None:
min_tweet = tweets[0]
continue_search = self.save_tweets(tweets)
# Our max tweet is the last tweet in the list
max_tweet = tweets[-1]
if min_tweet['tweet_id'] is not max_tweet['tweet_id']:
max_position = "TWEET-%s-%s" % (
max_tweet['tweet_id'], min_tweet['tweet_id'])
url = self.construct_url(query, max_position=max_position)
# Sleep for our rate_delay
sleep(self.rate_delay)
response = self.execute_search(url)
def execute_search(self, url):
"""
Executes a search to Twitter for the given URL
:param url: URL to search twitter with
:return: A JSON object with data from Twitter
"""
try:
# Specify a user agent to prevent Twitter from returning a profile
# card
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'
}
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req)
data = json.loads(response.read())
return data
# If we get a ValueError exception due to a request timing out, we sleep for our error delay, then make
# another attempt
except ValueError as e:
print e.message
print "Sleeping for %i" % self.error_delay
sleep(self.error_delay)
return self.execute_search(url)
@staticmethod
def parse_tweets(items_html):
"""
Parses Tweets from the given HTML
:param items_html: The HTML block with tweets
:return: A JSON list of tweets
"""
soup = BeautifulSoup(items_html, "html.parser")
tweets = []
for li in soup.find_all("li", class_='js-stream-item'):
# If our li doesn't have a tweet-id, we skip it as it's not going
# to be a tweet.
if 'data-item-id' not in li.attrs:
continue
tweet = {
'tweet_id': li['data-item-id'],
'text': None,
'user_id': None,
'user_screen_name': None,
'user_name': None,
'created_at': None,
'retweets': 0,
'favorites': 0
}
# Tweet Text
text_p = li.find("p", class_="tweet-text")
if text_p is not None:
tweet['text'] = text_p.get_text().encode('utf-8')
# Tweet User ID, User Screen Name, User Name
user_details_div = li.find("div", class_="tweet")
if user_details_div is not None:
tweet['user_id'] = user_details_div['data-user-id']
tweet['user_screen_name'] = user_details_div['data-user-id']
tweet['user_name'] = user_details_div['data-name']
# Tweet date
date_span = li.find("span", class_="_timestamp")
if date_span is not None:
tweet['created_at'] = float(date_span['data-time-ms'])
# Tweet Retweets
retweet_span = li.select(
"span.ProfileTweet-action--retweet > span.ProfileTweet-actionCount")
if retweet_span is not None and len(retweet_span) > 0:
tweet['retweets'] = int(
retweet_span[0]['data-tweet-stat-count'])
# Tweet Favourites
favorite_span = li.select(
"span.ProfileTweet-action--favorite > span.ProfileTweet-actionCount")
if favorite_span is not None and len(retweet_span) > 0:
tweet['favorites'] = int(
favorite_span[0]['data-tweet-stat-count'])
tweets.append(tweet)
return tweets
@staticmethod
def construct_url(query, max_position=None):
"""
For a given query, will construct a URL to search Twitter with
:param query: The query term used to search twitter
:param max_position: The max_position value to select the next pagination of tweets
:return: A string URL
"""
params = {
# Type Param
'f': 'tweets',
# Query Param
'q': query
}
# If our max_position param is not None, we add it to the parameters
if max_position is not None:
params['max_position'] = max_position
url_tuple = ('https', 'twitter.com', '/i/search/timeline',
'', urlencode(params), '')
return urlunparse(url_tuple)
@abstractmethod
def save_tweets(self, tweets):
"""
An abstract method that's called with a list of tweets.
When implementing this class, you can do whatever you want with these tweets.
"""
class TwitterSearchImpl(TwitterSearch):
def __init__(self, rate_delay, error_delay, csv_writer):
"""
:param rate_delay: How long to pause between calls to Twitter
:param error_delay: How long to pause when an error occurs
:param max_tweets: Maximum number of tweets to collect for this example
"""
super(TwitterSearchImpl, self).__init__(rate_delay, error_delay)
self.writer = csv_writer
def save_tweets(self, tweets):
"""
Prints out the tweets to a local CSV file.
"""
for tweet in tweets:
if tweet['created_at'] is not None:
time = datetime.datetime.fromtimestamp(
(tweet['created_at'] / 1000))
fmt = "%Y-%m-%d %H:%M:%S"
row = [tweet['text'], time.strftime(fmt), tweet['favorites'],
tweet['retweets'], tweet['tweet_id']]
self.writer.writerow(row)
return True
if __name__ == '__main__':
with open(OUT_FILE, "w") as f:
writer = csv.writer(f)
writer.writerow(["Text", "Date", "Favorites", "Retweets", "Tweet ID"])
twit = TwitterSearchImpl(0, 5, writer)
twit.search("from:realdonaldtrump")