Created
April 1, 2016 06:05
-
-
Save ararslan/7e5560fb3f021e5b98c81a0bbc3de2c3 to your computer and use it in GitHub Desktop.
Get election primary results for any Stack Exchange moderator election
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
from bs4 import BeautifulSoup | |
from urllib.request import urlopen | |
from urllib.parse import urlparse | |
def get_sites(): | |
response = urlopen("http://stackexchange.com/sites?tab=all") | |
soup = BeautifulSoup(response.read(), "html.parser") | |
for site in soup.find_all("a", attrs={"class": "noscript-link"}): | |
yield site.get("href") | |
def election_results(site: str, which: int = 1): | |
sites = {urlparse(url).netloc.split(".")[0]: url for url in get_sites()} | |
if not site in sites: | |
raise ValueError("Unrecognized site") | |
election_url = sites[site] + "/election/" + str(which) + "?tab=primary" | |
# May throw urllib.error.HTTPError | |
response = urlopen(election_url) | |
soup = BeautifulSoup(response.read(), "html.parser") | |
scores = [] | |
for tr in soup.find_all("tr"): | |
if tr.find("td", attrs={"class": "votecell"}): | |
username = tr.find(attrs={"class": "user-details"}).find("a").text | |
votes = int(tr.find(attrs={"class": "vote-count-post"}).text) | |
withdrew = "withdrew" in tr.find(attrs={"class": "user-action-time"}).text | |
scores.append((username, votes, withdrew)) | |
if not scores: | |
raise ValueError("Election #{} has not yet occurred for {}".format(which, site)) | |
max_name_len = max(len(g[0]) for g in scores) | |
max_vote_len = max(len(str(g[1])) for g in scores) | |
for user, votes, drop in sorted(scores, key=lambda x: x[1], reverse=True): | |
user_just = user.ljust(max_name_len) | |
votes_just = str(votes).rjust(max_vote_len) | |
print("{} {} {}".format(user_just, votes_just, "(withdrew)" if drop else "")) | |
if __name__ == "__main__": | |
site = input("Enter Stack Exchange site: ") | |
election_results(site) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment