|
| 1 | +import snscrape.modules.twitter as sntweets |
| 2 | +import sqlite3 |
| 3 | + |
| 4 | + |
| 5 | +def sql_connection(): |
| 6 | + """ |
| 7 | + Establishes a connection to the SQL file database |
| 8 | + :return connection object: |
| 9 | + """ |
| 10 | + con = sqlite3.connect('TwitterDatabase.db') |
| 11 | + return con |
| 12 | + |
| 13 | + |
| 14 | +def sql_table(con): |
| 15 | + """ |
| 16 | + Creates a table in the database (if it does not exist already) |
| 17 | + to store the tweet info |
| 18 | + :param con: |
| 19 | + :return: |
| 20 | + """ |
| 21 | + cur = con.cursor() |
| 22 | + cur.execute("CREATE TABLE IF NOT EXISTS tweets(HASHTAG text, USERNAME text," |
| 23 | + " CONTENT text, URL text)") |
| 24 | + con.commit() |
| 25 | + |
| 26 | + |
| 27 | +def sql_insert_table(con, entities): |
| 28 | + """ |
| 29 | + Inserts the desired data into the table to store tweet info |
| 30 | + :param con: |
| 31 | + :param entities: |
| 32 | + :return: |
| 33 | + """ |
| 34 | + cur = con.cursor() |
| 35 | + cur.execute('INSERT INTO tweets(HASHTAG, USERNAME, CONTENT, ' |
| 36 | + 'URL) VALUES(?, ?, ?, ?)', entities) |
| 37 | + con.commit() |
| 38 | + |
| 39 | + |
| 40 | +con = sql_connection() |
| 41 | +sql_table(con) |
| 42 | + |
| 43 | +while 1: |
| 44 | + tag = input('\n\nEnter a hashtag: #') |
| 45 | + max_count = int(input('Enter maximum number of tweets to be listed: ')) |
| 46 | + |
| 47 | + count = 0 |
| 48 | + # snscrape uses the given string of hashtag to find the desired amount of |
| 49 | + # tweets and associated info |
| 50 | + for i in sntweets.TwitterSearchScraper('#' + tag).get_items(): |
| 51 | + count += 1 |
| 52 | + entities = ('#'+tag, i.username, i.content, i.url) |
| 53 | + sql_insert_table(con, entities) |
| 54 | + |
| 55 | + if count == max_count: |
| 56 | + break |
| 57 | + |
| 58 | + print('Done!') |
| 59 | + |
| 60 | + ans = input('Press (y) to continue or any other key to exit: ').lower() |
| 61 | + if ans == 'y': |
| 62 | + continue |
| 63 | + else: |
| 64 | + print('Exiting..') |
| 65 | + break |
| 66 | + |
0 commit comments