|
| 1 | +import datetime |
| 2 | +import http.cookiejar |
| 3 | +import json |
| 4 | +import re |
| 5 | +import uuid |
| 6 | +import urllib.parse, urllib.request, urllib.error |
| 7 | +from pyquery import PyQuery |
| 8 | +from tweets import Tweet |
| 9 | + |
| 10 | + |
| 11 | +def get_tweets(search_params, current_position): |
| 12 | + """ |
| 13 | + Build search Query and get the tweets |
| 14 | + :param search_params: SearchParams object |
| 15 | + :param current_position: Min position where you want to retrieve the tweets from |
| 16 | + :return: twitter json_data |
| 17 | + """ |
| 18 | + base_url = "https://twitter.com/i/search/timeline?f=tweets&q={}&src=typd&{}max_position={}" |
| 19 | + query = '' |
| 20 | + query = query + (' ' + search_params.search_query) if search_params.search_query else query |
| 21 | + query = query + (' from:' + search_params.account_name) if search_params.account_name else query |
| 22 | + query = query + (' since:' + search_params.since_date) if search_params.since_date else query |
| 23 | + query = query + (' until:' + search_params.until_date) if search_params.until_date else query |
| 24 | + lang = ('lang=' + search_params.language + '&') if search_params.language else '' |
| 25 | + |
| 26 | + query = urllib.parse.quote(query) |
| 27 | + base_url = base_url.format(query, lang, current_position) |
| 28 | + print(base_url) |
| 29 | + |
| 30 | + cookie_jar = http.cookiejar.CookieJar() |
| 31 | + headers = [ |
| 32 | + ('Host', "twitter.com"), |
| 33 | + ('User-Agent', "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"), |
| 34 | + ('Accept', "application/json, text/javascript, */*; q=0.01"), |
| 35 | + ('Accept-Language', "en-US;q=0.7,en;q=0.3"), |
| 36 | + ('X-Requested-With', "XMLHttpRequest"), |
| 37 | + ('Referer', base_url), |
| 38 | + ('Connection', "keep-alive") |
| 39 | + ] |
| 40 | + |
| 41 | + attempts = 0 |
| 42 | + response = '' |
| 43 | + while attempts < 10: |
| 44 | + try: |
| 45 | + if search_params.proxy: |
| 46 | + print('Using IP {}'.format(search_params.proxy)) |
| 47 | + proxy = urllib.request.ProxyHandler({'http': search_params.proxy, 'https': search_params.proxy}) |
| 48 | + opener = urllib.request.build_opener(proxy, urllib.request.HTTPCookieProcessor(cookie_jar)) |
| 49 | + else: |
| 50 | + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie_jar)) |
| 51 | + opener.addheaders = headers |
| 52 | + response = opener.open(base_url) |
| 53 | + break |
| 54 | + except Exception: |
| 55 | + attempts += 1 |
| 56 | + print('Retrying with different IP !!') |
| 57 | + |
| 58 | + json_res = response.read() |
| 59 | + json_data = json.loads(json_res.decode()) |
| 60 | + return json_data |
| 61 | + |
| 62 | + |
| 63 | +def parse_json(search_params): |
| 64 | + """ |
| 65 | + Parse the json tweet |
| 66 | + :param search_params: SearchParams object |
| 67 | + :return: void |
| 68 | + """ |
| 69 | + min_position = get_last_search_position(search_params.log_file_name) |
| 70 | + count = 0 |
| 71 | + while True: |
| 72 | + json_res = get_tweets(search_params, min_position) |
| 73 | + if len(json_res['items_html'].strip()) == 0: |
| 74 | + break |
| 75 | + |
| 76 | + min_position = json_res['min_position'] |
| 77 | + search_params.logging.info('min_pos - {}'.format(min_position)) |
| 78 | + item = json_res['items_html'] |
| 79 | + scraped_tweets = PyQuery(item) |
| 80 | + scraped_tweets.remove('div.withheld-tweet') |
| 81 | + tweets = scraped_tweets('div.js-stream-tweet') |
| 82 | + |
| 83 | + for tweet_html in tweets: |
| 84 | + print(count) |
| 85 | + tweet_py_query = PyQuery(tweet_html) |
| 86 | + name = tweet_py_query.attr("data-name") |
| 87 | + screen_name = tweet_py_query.attr("data-screen-name") |
| 88 | + tweet_id = tweet_py_query.attr("data-tweet-id") |
| 89 | + tweet_text = re.sub(r"\s+", " ", |
| 90 | + tweet_py_query("p.js-tweet-text").text().replace('# ', '#').replace('@ ', '@')) |
| 91 | + tweet_date_time = int(tweet_py_query("small.time span.js-short-timestamp").attr("data-time")) |
| 92 | + tweet_date_time = datetime.datetime.fromtimestamp(tweet_date_time) |
| 93 | + retweet_count = int(tweet_py_query("span.ProfileTweet-action--retweet span.ProfileTweet-actionCount").attr( |
| 94 | + "data-tweet-stat-count").replace(",", "")) |
| 95 | + favorites_count = int( |
| 96 | + tweet_py_query("span.ProfileTweet-action--favorite span.ProfileTweet-actionCount").attr( |
| 97 | + "data-tweet-stat-count").replace(",", "")) |
| 98 | + permalink = 'https://twitter.com' + tweet_py_query.attr("data-permalink-path") |
| 99 | + |
| 100 | + tweet = Tweet(str(uuid.uuid4()), name, screen_name, tweet_id, tweet_text, tweet_date_time, retweet_count, |
| 101 | + favorites_count, permalink) |
| 102 | + # Now Write to OP or save to DB |
| 103 | + write_op(search_params.op, tweet) |
| 104 | + count += 1 |
| 105 | + # sleep(5) |
| 106 | + if 0 < search_params.max_retrieval_count <= count: |
| 107 | + break |
| 108 | + |
| 109 | + |
| 110 | +def write_op(op_file, tweet): |
| 111 | + """ |
| 112 | + Writing tweets to some output file |
| 113 | + :param op_file: op_file name |
| 114 | + :param tweet: Tweet object |
| 115 | + :return: void |
| 116 | + """ |
| 117 | + with open(op_file, 'a+', encoding='utf-8') as f: |
| 118 | + # UUID, tweet_id, user_name, screen_name, tweet, date_time, retweet_count, fav_count, link |
| 119 | + f.write( |
| 120 | + ('%s;%s;%s;%s;%s;%s;%d;%d;%s\n' % (tweet.uuid, tweet.tweet_id, tweet.name, tweet.screen_name, tweet.tweet, |
| 121 | + tweet.date_time.strftime("%Y-%m-%d %H:%M"), tweet.retweet_count, |
| 122 | + tweet.favourites_count, tweet.link))) |
| 123 | + |
| 124 | + |
| 125 | +def get_last_search_position(logger_file): |
| 126 | + """ |
| 127 | + Required for resuming the previous search operation |
| 128 | + :param logger_file: Logger file name |
| 129 | + :return: Last position id |
| 130 | + """ |
| 131 | + with open(logger_file, 'r+') as f: |
| 132 | + lines = f.read().splitlines() |
| 133 | + try: |
| 134 | + last_pos = lines[-1].split(' - ')[1] |
| 135 | + except IndexError: |
| 136 | + last_pos = '' |
| 137 | + return last_pos |
0 commit comments