aec-canning-2015.py
· 849 B · Python
Raw
import requests
from bs4 import BeautifulSoup as Soup
from tabulate import tabulate
import sys
headers = ["Candidate", "Party", "Votes", "%", "Swing (%)"]
def get_data():
soup = Soup(requests.get("http://vtr.aec.gov.au/HouseDivisionFirstPrefs-18126-236.htm").text, "html.parser")
for row in soup.findAll('tr', id=lambda x: x and x.startswith("repeaterCandidates")):
yield [td.text for td in row.findAll('td')]
def main():
if len(sys.argv) > 1:
if not sys.argv[1].isdigit():
print "Usage: {} <column number to sort on>".format(sys.argv[0])
return 1
col = int(sys.argv[1])
else:
col = 3
data = [d for d in get_data()]
print tabulate(sorted(data, key=lambda x: float(x[col]), reverse=True), headers=headers)
return 0
if __name__ == "__main__":
sys.exit(main())
| 1 | import requests |
| 2 | from bs4 import BeautifulSoup as Soup |
| 3 | from tabulate import tabulate |
| 4 | import sys |
| 5 | |
| 6 | headers = ["Candidate", "Party", "Votes", "%", "Swing (%)"] |
| 7 | |
| 8 | def get_data(): |
| 9 | soup = Soup(requests.get("http://vtr.aec.gov.au/HouseDivisionFirstPrefs-18126-236.htm").text, "html.parser") |
| 10 | for row in soup.findAll('tr', id=lambda x: x and x.startswith("repeaterCandidates")): |
| 11 | yield [td.text for td in row.findAll('td')] |
| 12 | |
| 13 | def main(): |
| 14 | if len(sys.argv) > 1: |
| 15 | if not sys.argv[1].isdigit(): |
| 16 | print "Usage: {} <column number to sort on>".format(sys.argv[0]) |
| 17 | return 1 |
| 18 | col = int(sys.argv[1]) |
| 19 | else: |
| 20 | col = 3 |
| 21 | data = [d for d in get_data()] |
| 22 | print tabulate(sorted(data, key=lambda x: float(x[col]), reverse=True), headers=headers) |
| 23 | return 0 |
| 24 | |
| 25 | if __name__ == "__main__": |
| 26 | sys.exit(main()) |