/
scraper.py
158 lines (132 loc) · 4.8 KB
/
scraper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# -*- coding: utf-8 -*-
#### IMPORTS 1.0
import os
import re
import scraperwiki
import urllib2
from datetime import datetime
from bs4 import BeautifulSoup
#### FUNCTIONS 1.0
def validateFilename(filename):
filenameregex = '^[a-zA-Z0-9]+_[a-zA-Z0-9]+_[a-zA-Z0-9]+_[0-9][0-9][0-9][0-9]_[0-9QY][0-9]$'
dateregex = '[0-9][0-9][0-9][0-9]_[0-9QY][0-9]'
validName = (re.search(filenameregex, filename) != None)
found = re.search(dateregex, filename)
if not found:
return False
date = found.group(0)
now = datetime.now()
year, month = date[:4], date[5:7]
validYear = (2000 <= int(year) <= now.year)
if 'Q' in date:
validMonth = (month in ['Q0', 'Q1', 'Q2', 'Q3', 'Q4'])
elif 'Y' in date:
validMonth = (month in ['Y1'])
else:
try:
validMonth = datetime.strptime(date, "%Y_%m") < now
except:
return False
if all([validName, validYear, validMonth]):
return True
def validateURL(url):
try:
r = urllib2.urlopen(url)
count = 1
while r.getcode() == 500 and count < 4:
print ("Attempt {0} - Status code: {1}. Retrying.".format(count, r.status_code))
count += 1
r = urllib2.urlopen(url)
sourceFilename = r.headers.get('Content-Disposition')
if sourceFilename:
ext = os.path.splitext(sourceFilename)[1].replace('"', '').replace(';', '').replace(' ', '')
elif 'application/pdf' in r.headers.get('Content-Type'):
ext = '.pdf'
else:
ext = os.path.splitext(url)[1]
validURL = r.getcode() == 200
if not ext:
ext = '.csv'
validFiletype = ext.lower() in ['.csv', '.xls', '.xlsx', '.pdf']
return validURL, validFiletype
except:
print ("Error validating URL.")
return False, False
def validate(filename, file_url):
validFilename = validateFilename(filename)
validURL, validFiletype = validateURL(file_url)
if not validFilename:
print filename, "*Error: Invalid filename*"
print file_url
return False
if not validURL:
print filename, "*Error: Invalid URL*"
print file_url
return False
if not validFiletype:
print filename, "*Error: Invalid filetype*"
print file_url
return False
return True
def convert_mth_strings ( mth_string ):
month_numbers = {'JAN': '01', 'FEB': '02', 'MAR':'03', 'APR':'04', 'MAY':'05', 'JUN':'06', 'JUL':'07', 'AUG':'08', 'SEP':'09','OCT':'10','NOV':'11','DEC':'12' }
for k, v in month_numbers.items():
mth_string = mth_string.replace(k, v)
return mth_string
#### VARIABLES 1.0
entity_id = "E1433_HBC_gov"
url = "https://www.hastings.gov.uk/my_council/transparency/budgets/"
errors = 0
data = []
#### READ HTML 1.0
html = urllib2.urlopen(url)
soup = BeautifulSoup(html, 'lxml')
#### SCRAPE DATA
links = soup.find('a', attrs={'title':'Financial Management'}).parent.find_next('ul').find_all('a')
for link in links:
if 'csv' in link['href']:
file_name = link.text.strip()
if 'http' not in link['href']:
url = 'https://www.hastings.gov.uk' + link['href']
else:
url = link['href']
match = re.match(r'.*([1-3][0-9]{3})', file_name)
if match is not None:
csvYr = match.group(1)
csvMth = file_name.split(':')[-1].strip()[:3]
csvMth = convert_mth_strings(csvMth.upper())
data.append([csvYr, csvMth, url])
pdf_links = soup.find('a', attrs={'title':'Supplier payments: January 2012 csv'}).parent.find_all_next('li')
for pdf_link in pdf_links:
pdf_name = pdf_link.find('a')
if pdf_name and 'Supplier payments' in pdf_name.text:
file_name = pdf_link.find('a').text
match = re.match(r'.*([1-3][0-9]{3})', file_name)
if match is not None:
csvYr = match.group(1)
csvMth = file_name.split(':')[-1].strip()[:3]
if 'April to June 2010' in file_name:
csvMth = 'Q2'
url = pdf_link.find('a')['href']
csvMth = convert_mth_strings(csvMth.upper())
data.append([csvYr, csvMth, url])
feb_url = soup.find('a', attrs={'title':'Supplier payments: February 2012 pdf'})['href']
csvMth = 'Feb'
csvYr = '2012'
csvMth = convert_mth_strings(csvMth.upper())
data.append([csvYr, csvMth, url])
#### STORE DATA 1.0
for row in data:
csvYr, csvMth, url = row
filename = entity_id + "_" + csvYr + "_" + csvMth
todays_date = str(datetime.now())
file_url = url.strip()
valid = validate(filename, file_url)
if valid == True:
scraperwiki.sqlite.save(unique_keys=['l'], data={"l": file_url, "f": filename, "d": todays_date })
print filename
else:
errors += 1
if errors > 0:
raise Exception("%d errors occurred during scrape." % errors)
#### EOF