Skip to content

Instantly share code, notes, and snippets.

@kmonsoor
Last active December 19, 2015 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmonsoor/9b2fe84309e34725cd6d to your computer and use it in GitHub Desktop.
Save kmonsoor/9b2fe84309e34725cd6d to your computer and use it in GitHub Desktop.
StackOverflow to Github user mapping
#!/usr/bin/python
__author__ = 'Khaled Monsoor <k@kmonsoor.com>'
__license__ = 'The MIT License: <http://kmonsoor.mit-license.org/>'
import json
import requests
def stackoverflow_to_github_user(stackoverflow_id):
'''
Given a numerical `userID` on StackOverflow, it returns user's username on Github, if available.
If `userID` is invalid on StackOverflow, it raise `ValueError`.
If `userID` is valid on StackOverflow but has no Github info associated, \
it will return empty string('').
'''
url = 'http://stackoverflow.com/users/' + str(int(stackoverflow_id))
response = requests.get(url)
if response.status_code != 200:
raise ValueError('Invalid user ID: {}'.format(stackoverflow_id))
soup = BeautifulSoup(response.content)
github_username = ''
for tag in soup.find_all('a', attrs={'class': 'url'}):
if 'github' in tag.get('href', ''):
github_username = tag['href'].split('/')[-1]
return github_username
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment