Last active
December 19, 2015 20:51
-
-
Save kmonsoor/9b2fe84309e34725cd6d to your computer and use it in GitHub Desktop.
StackOverflow to Github user mapping
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
#!/usr/bin/python | |
__author__ = 'Khaled Monsoor <[email protected]>' | |
__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