-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit c9e278a
Showing
11 changed files
with
332 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
config.py | ||
.venv/ | ||
# C extensions | ||
*.so | ||
.DS_Store | ||
|
||
.idea/ | ||
|
||
# Distribution / packaging | ||
.Python | ||
env/ | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
.idea/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*,cover | ||
.hypothesis/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
target/ | ||
|
||
# IPython Notebook | ||
.ipynb_checkpoints | ||
|
||
# pyenv | ||
.python-version | ||
|
||
# celery beat schedule file | ||
celerybeat-schedule | ||
|
||
# dotenv | ||
.env | ||
|
||
# virtualenv | ||
venv/ | ||
ENV/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# redis | ||
redis-stable/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2017 Shivam Mathur | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# TwitterScraper | ||
Scrape tweets from twitter | ||
|
||
## Features | ||
- Scrape old tweets | ||
- Scrape by username | ||
- Scrape top tweets |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import twitter_scraper | ||
import json | ||
|
||
|
||
def main(): | ||
def build_list(t, tweet_list): | ||
tweet_list.append( | ||
{ | ||
"username": t.username, | ||
"tweet": t.retweets, | ||
"retweets": t.text, | ||
"mentions": t.mentions, | ||
"hashtags": t.hashtags | ||
} | ||
) | ||
return tweet_list | ||
|
||
def print_to_file(data, filename): | ||
try: | ||
with open(filename + '.json', 'a') as f: | ||
f.write(data) | ||
return True | ||
except BaseException as e: | ||
print e | ||
|
||
search_term = '#earthquake' | ||
search_params = twitter_scraper.scraper.SearchParams().set_search(search_term).set_since("2017-02-01").set_until( | ||
"2017-03-01") | ||
tweets = twitter_scraper.scraper.Scraper.get_tweets(search_params) | ||
|
||
t_list = [] | ||
for tweet in tweets: | ||
t_list = build_list(tweet, t_list) | ||
json_data = json.dumps(t_list, indent=4) | ||
print_to_file(json_data, search_term) | ||
|
||
if __name__ == '__main__': | ||
main() |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
import tweet | ||
import scraper |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from search_params import SearchParams | ||
from scraper import Scraper |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
import urllib | ||
import urllib2 | ||
import json | ||
import re | ||
import datetime | ||
import sys | ||
import cookielib | ||
from pyquery import PyQuery | ||
from .. import tweet | ||
|
||
|
||
class Scraper: | ||
def __init__(self): | ||
pass | ||
|
||
@staticmethod | ||
def get_tweets(search_params, receive_buffer=None, buffer_length=100): | ||
refresh_cursor = '' | ||
|
||
results = [] | ||
results_aux = [] | ||
cookie_jar = cookielib.CookieJar() | ||
|
||
if hasattr(search_params, 'username') and ( | ||
search_params.username.startswith("\'") or search_params.username.startswith("\"")) and ( | ||
search_params.username.endswith("\'") or search_params.username.endswith("\"") | ||
): | ||
search_params.username = search_params.username[1:-1] | ||
|
||
active = True | ||
|
||
while active: | ||
json_response = Scraper.get_json_response(search_params, refresh_cursor, cookie_jar) | ||
if len(json_response['items_html'].strip()) == 0: | ||
break | ||
|
||
refresh_cursor = json_response['min_position'] | ||
tweets = PyQuery(json_response['items_html'])('div.js-stream-tweet') | ||
|
||
if len(tweets) == 0: | ||
break | ||
|
||
for tweetHTML in tweets: | ||
tweet_pq = PyQuery(tweetHTML) | ||
tweet_object = tweet.Tweet() | ||
|
||
username_tweet = tweet_pq("span.username.js-action-profile-name b").text() | ||
txt = re.sub(r"\s+", " ", tweet_pq("p.js-tweet-text").text().replace('# ', '#').replace('@ ', '@')) | ||
retweets = int(tweet_pq("span.ProfileTweet-action--retweet span.ProfileTweet-actionCount").attr( | ||
"data-tweet-stat-count").replace(",", "")) | ||
favorites = int(tweet_pq("span.ProfileTweet-action--favorite span.ProfileTweet-actionCount").attr( | ||
"data-tweet-stat-count").replace(",", "")) | ||
date_sec = int(tweet_pq("small.time span.js-short-timestamp").attr("data-time")) | ||
tweet_id = tweet_pq.attr("data-tweet-id") | ||
permalink = tweet_pq.attr("data-permalink-path") | ||
|
||
geo = '' | ||
geo_span = tweet_pq('span.Tweet-geo') | ||
if len(geo_span) > 0: | ||
geo = geo_span.attr('title') | ||
|
||
tweet_object.id = tweet_id | ||
tweet_object.permalink = 'https://twitter.com' + permalink | ||
tweet_object.username = username_tweet | ||
tweet_object.text = txt | ||
tweet_object.date = datetime.datetime.fromtimestamp(date_sec) | ||
tweet_object.retweets = retweets | ||
tweet_object.favorites = favorites | ||
tweet_object.mentions = " ".join(re.compile('(@\\w*)').findall(tweet_object.text)) | ||
tweet_object.hashtags = " ".join(re.compile('(#\\w*)').findall(tweet_object.text)) | ||
tweet_object.geo = geo | ||
|
||
results.append(tweet_object) | ||
results_aux.append(tweet_object) | ||
|
||
if receive_buffer and len(results_aux) >= buffer_length: | ||
receive_buffer(results_aux) | ||
results_aux = [] | ||
|
||
if 0 < search_params.maxTweets <= len(results): | ||
active = False | ||
break | ||
|
||
if receive_buffer and len(results_aux) > 0: | ||
receive_buffer(results_aux) | ||
|
||
return results | ||
|
||
@staticmethod | ||
def get_json_response(search_params, refresh_cursor, cookie_jar): | ||
url = "https://twitter.com/i/search/timeline?f=tweets&q=%s&src=typd&max_position=%s" | ||
|
||
url_get_data = '' | ||
if hasattr(search_params, 'username'): | ||
url_get_data += ' from:' + search_params.username | ||
|
||
if hasattr(search_params, 'since'): | ||
url_get_data += ' since:' + search_params.since | ||
|
||
if hasattr(search_params, 'until'): | ||
url_get_data += ' until:' + search_params.until | ||
|
||
if hasattr(search_params, 'querySearch'): | ||
url_get_data += ' ' + search_params.querySearch | ||
|
||
if hasattr(search_params, 'topTweets'): | ||
if search_params.topTweets: | ||
url = "https://twitter.com/i/search/timeline?q=%s&src=typd&max_position=%s" | ||
|
||
url %= (urllib.quote(url_get_data), refresh_cursor) | ||
|
||
headers = [ | ||
('Host', "twitter.com"), | ||
('User-Agent', "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"), | ||
('Accept', "application/json, text/javascript, */*; q=0.01"), | ||
('Accept-Language', "de,en-US;q=0.7,en;q=0.3"), | ||
('X-Requested-With', "XMLHttpRequest"), | ||
('Referer', url), | ||
('Connection', "keep-alive") | ||
] | ||
|
||
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar)) | ||
opener.addheaders = headers | ||
|
||
try: | ||
response = opener.open(url) | ||
json_response = response.read() | ||
except: | ||
print "url: https://twitter.com/search?q=%s&src=typd" % urllib.quote(url_get_data) | ||
sys.exit() | ||
|
||
json_data = json.loads(json_response) | ||
|
||
return json_data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
class SearchParams: | ||
def __init__(self): | ||
self.maxTweets = 0 | ||
|
||
def set_username(self, username): | ||
self.username = username | ||
return self | ||
|
||
def set_since(self, since): | ||
self.since = since | ||
return self | ||
|
||
def set_until(self, until): | ||
self.until = until | ||
return self | ||
|
||
def set_search(self, query_search): | ||
self.querySearch = query_search | ||
return self | ||
|
||
def set_max_tweets(self, max_tweets): | ||
self.maxTweets = max_tweets | ||
return self | ||
|
||
def set_top_tweets(self, top_tweets): | ||
self.topTweets = top_tweets | ||
return self |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from tweet import Tweet |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
class Tweet: | ||
def __init__(self): | ||
pass |