Created
January 31, 2019 21:41
-
-
Save timothycarambat/771c22bd376b55bf3b24add0e8b59b42 to your computer and use it in GitHub Desktop.
Twitter Handle retriever by User ID. For u/mahonmadasulah. https://www.reddit.com/r/programmingrequests/comments/altr67/request_convert_list_of_twitter_user_ids_into/
This file contains hidden or 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
# You should have a .txt file named users.txt in the same directory you run this script in. | |
# You will need to have install beautifulsoup4 as well as rquest | |
from bs4 import BeautifulSoup as bs | |
import requests | |
import csv | |
twitter_ids = [] | |
twitter_handles = {} | |
user_file = open('users.txt', 'r') | |
for id in user_file: | |
# dont get empty lines from .txt file and strip the newline character | |
if id != '\n': | |
twitter_ids.append(id.strip('\n')) | |
for id in twitter_ids: | |
print("Fetching @Handle for ID %s" % id) | |
url = "http://www.twitter.com/intent/user?user_id=%s" % id | |
result = requests.get(url) | |
if result.status_code == requests.codes.not_found: | |
print("ID %s returned a 404.\n" % id) | |
continue | |
soup = bs(result.content, 'html.parser') | |
handle_element = soup.find_all('span', {'class':'nickname'}) | |
if len(handle_element) > 0: | |
handle = handle_element[0].text | |
twitter_handles[id] = handle | |
print("ID %s is %s\n" % (id, handle)) | |
else: | |
print("Couldnt Find a handle for ID %s. User is either suspended or invalid.\n" % id) | |
total_handles = len(twitter_handles.keys()) | |
total_ids = len(twitter_ids) | |
print("A Total of %d were found out of %d IDs" % (total_handles, total_ids)) | |
with open("output.csv", "wb") as f: | |
writer = csv.writer(f) | |
for uid in twitter_handles.keys(): | |
writer.writerow([uid, twitter_handles[uid]]) |
This file contains hidden or 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
15826896 | |
14785236 | |
14787878 | |
78547820 | |
00000000 | |
00000014 | |
00004444 | |
88888888 | |
19191919 | |
00000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment