Automatically exported from code.google.com/p/planningalerts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

354 lines
16 KiB

  1. #!/usr/local/bin/python
  2. import urllib2
  3. import urlparse
  4. from datetime import date
  5. import datetime
  6. import re
  7. from BeautifulSoup import BeautifulSoup
  8. # Adding this to try to help Surrey Heath - Duncan 14/9/2007
  9. import cookielib
  10. cookie_jar = cookielib.CookieJar()
  11. ################
  12. import MultipartPostHandler
  13. # this is not mine, or part of standard python (though it should be!)
  14. # it comes from http://pipe.scs.fsu.edu/PostHandler/MultipartPostHandler.py
  15. from PlanningUtils import getPostcodeFromText, PlanningAuthorityResults, PlanningApplication
  16. date_format = "%d/%m/%Y"
  17. #This is to get the system key out of the info url
  18. system_key_regex = re.compile("TheSystemkey=(\d*)", re.IGNORECASE)
  19. # We allow the optional > for Bridgnorth, which doesn't have broken html
  20. end_head_regex = re.compile("</head>?", re.IGNORECASE)
  21. class AcolnetParser:
  22. received_date_format = "%d/%m/%Y"
  23. comment_qs_template = "ACTION=UNWRAP&RIPNAME=Root.PgeCommentForm&TheSystemkey=%s"
  24. # There is no online comment facility in these, so we provide an
  25. # appropriate email address instead
  26. comments_email_address = None
  27. # The optional amp; is to cope with Oldham, which seems to have started
  28. # quoting this url.
  29. action_regex = re.compile("<form[^>]*action=\"([^\"]*ACTION=UNWRAP&(?:amp;)?RIPSESSION=[^\"]*)\"[^>]*>", re.IGNORECASE)
  30. def _getResultsSections(self, soup):
  31. """In most cases, there is a table per app."""
  32. return soup.findAll("table", {"class": "results-table"})
  33. def _getCouncilReference(self, app_table):
  34. # return app_table.findAll("a")[1].string.strip()
  35. return app_table.a.string.strip()
  36. def _getDateReceived(self, app_table):
  37. date_str = ''.join(app_table.find(text="Registration Date:").findNext("td").string.strip().split())
  38. return datetime.datetime.strptime(date_str, self.received_date_format)
  39. def _getAddress(self, app_table):
  40. return app_table.find(text="Location:").findNext("td").string.strip()
  41. def _getDescription(self, app_table):
  42. return app_table.find(text="Proposal:").findNext("td").string.strip()
  43. def _getInfoUrl(self, app_table):
  44. """Returns the info url for this app.
  45. We also set the system key on self._current_application,
  46. as we'll need that for the comment url.
  47. """
  48. url = app_table.a['href']
  49. self._current_application.system_key = system_key_regex.search(url).groups()[0]
  50. return urlparse.urljoin(self.base_url, url)
  51. def _getCommentUrl(self, app_table):
  52. """This must be run after _getInfoUrl"""
  53. if self.comments_email_address:
  54. return self.comments_email_address
  55. split_info_url = urlparse.urlsplit(self._current_application.info_url)
  56. comment_qs = self.comment_qs_template %self._current_application.system_key
  57. return urlparse.urlunsplit(split_info_url[:3] + (comment_qs,) + split_info_url[4:])
  58. def __init__(self,
  59. authority_name,
  60. authority_short_name,
  61. base_url,
  62. debug=False):
  63. self.authority_name = authority_name
  64. self.authority_short_name = authority_short_name
  65. self.base_url = base_url
  66. self.debug = debug
  67. # This in where we store the results
  68. self._results = PlanningAuthorityResults(self.authority_name, self.authority_short_name)
  69. # This will store the planning application we are currently working on.
  70. self._current_application = None
  71. def _cleanupHTML(self, html):
  72. """This method should be overridden in subclasses to perform site specific
  73. HTML cleanup."""
  74. return html
  75. def _getSearchResponse(self):
  76. # It looks like we sometimes need to do some stuff to get around a
  77. # javascript redirect and cookies.
  78. search_form_request = urllib2.Request(self.base_url)
  79. search_form_response = urllib2.urlopen(search_form_request)
  80. return search_form_response
  81. def getResultsByDayMonthYear(self, day, month, year):
  82. # first we fetch the search page to get ourselves some session info...
  83. search_form_response = self._getSearchResponse()
  84. search_form_contents = search_form_response.read()
  85. # This sometimes causes a problem in HTMLParser, so let's just get the link
  86. # out with a regex...
  87. groups = self.action_regex.search(search_form_contents).groups()
  88. action = groups[0]
  89. #print action
  90. # This is to handle the amp; which seems to have appeared in this
  91. # url on the Oldham site
  92. action = ''.join(action.split('amp;'))
  93. action_url = urlparse.urljoin(self.base_url, action)
  94. print action_url
  95. our_date = date(year, month, day)
  96. search_data = {"regdate1": our_date.strftime(date_format),
  97. "regdate2": our_date.strftime(date_format),
  98. }
  99. opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
  100. response = opener.open(action_url, search_data)
  101. results_html = response.read()
  102. # This is for doing site specific html cleanup
  103. results_html = self._cleanupHTML(results_html)
  104. #some javascript garbage in the header upsets HTMLParser,
  105. #so we'll just have the body
  106. just_body = "<html>" + end_head_regex.split(results_html)[-1]
  107. #self.feed(just_body)
  108. soup = BeautifulSoup(just_body)
  109. # Each app is in a table of it's own.
  110. results_tables = self._getResultsSections(soup)
  111. for app_table in results_tables:
  112. self._current_application = PlanningApplication()
  113. self._current_application.council_reference = self._getCouncilReference(app_table)
  114. self._current_application.address = self._getAddress(app_table)
  115. # Get the postcode from the address
  116. self._current_application.postcode = getPostcodeFromText(self._current_application.address)
  117. self._current_application.description = self._getDescription(app_table)
  118. self._current_application.info_url = self._getInfoUrl(app_table)
  119. self._current_application.comment_url = self._getCommentUrl(app_table)
  120. self._current_application.date_received = self._getDateReceived(app_table)
  121. self._results.addApplication(self._current_application)
  122. return self._results
  123. def getResults(self, day, month, year):
  124. return self.getResultsByDayMonthYear(int(day), int(month), int(year)).displayXML()
  125. class BassetlawParser(AcolnetParser):
  126. comments_email_address = "planning@bassetlaw.gov.uk"
  127. def _cleanupHTML(self, html):
  128. """There is a broken div in this page. We don't need any divs, so
  129. let's get rid of them all."""
  130. div_regex = re.compile("</?div[^>]*>", re.IGNORECASE)
  131. return div_regex.sub('', html)
  132. class BridgnorthParser(AcolnetParser):
  133. def _getResultsSections(self, soup):
  134. return soup.findAll("table", {"class": "app"})
  135. def _getCouncilReference(self, app_table):
  136. return app_table.a.string.split()[-1]
  137. def _getCommentUrl(self, app_table):
  138. """This must be run after _getInfoUrl"""
  139. #http://www2.bridgnorth-dc.gov.uk/planning/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.PgeCommentForm&TheSystemkey=46958
  140. return self._current_application.info_url.replace("NewPages", "PgeCommentForm")
  141. # Cambridgeshire, although an Acolnet site, is so different that it
  142. # may as well be handled completely separately.
  143. class CanterburyParser(AcolnetParser):
  144. """Here the apps are one row each in a big table."""
  145. def _getResultsSections(self, soup):
  146. return soup.find("table", {"class": "results-table"}).findAll("tr")[1:]
  147. def _getDateReceived(self, app_table):
  148. date_str = app_table.findAll("td")[3].string.strip()
  149. return datetime.datetime.strptime(date_str, self.received_date_format)
  150. def _getAddress(self, app_table):
  151. return app_table.findAll("td")[1].string.strip()
  152. def _getDescription(self, app_table):
  153. return app_table.findAll("td")[2].string.strip()
  154. #Kensington and chelsea is sufficiently different, it may as well be handled separately
  155. # Mid Bedfordshire - there is an acolnet here, but you have to have a username
  156. # and password to access it!
  157. class OldhamParser(AcolnetParser):
  158. def _cleanupHTML(self, html):
  159. """There is a bad table end tag in this one.
  160. Fix it before we start"""
  161. bad_table_end = '</table summary="Copyright">'
  162. good_table_end = '</table>'
  163. return html.replace(bad_table_end, good_table_end)
  164. class SouthwarkParser(AcolnetParser):
  165. def _getDateReceived(self, app_table):
  166. date_str = ''.join(app_table.find(text="Statutory start date:").findNext("td").string.strip().split())
  167. return datetime.datetime.strptime(date_str, self.received_date_format)
  168. class SurreyHeathParser(AcolnetParser):
  169. # This is not working yet.
  170. # _getSearchResponse is an attempt to work around
  171. # cookies and a javascript redirect.
  172. # I may have a bit more of a go at this at some point if I have time.
  173. case_number_tr = 1 # this one can be got by the td class attribute
  174. reg_date_tr = 2
  175. location_tr = 4
  176. proposal_tr = 5
  177. comments_email_address = "development-control@surreyheath.gov.uk"
  178. def _getSearchResponse(self):
  179. # It looks like we sometimes need to do some stuff to get around a
  180. # javascript redirect and cookies.
  181. search_form_request = urllib2.Request(self.base_url)
  182. # Lying about the user-agent doesn't seem to help.
  183. #search_form_request.add_header("user-agent", "Mozilla/5.0 (compatible; Konqu...L/3.5.6 (like Gecko) (Kubuntu)")
  184. search_form_response = urllib2.urlopen(search_form_request)
  185. cookie_jar.extract_cookies(search_form_response, search_form_request)
  186. print search_form_response.geturl()
  187. print search_form_response.info()
  188. print search_form_response.read()
  189. # validate_url = "https://www.public.surreyheath-online.gov.uk/whalecom7cace3215643e22bb7b0b8cc97a7/whalecom0/InternalSite/Validate.asp"
  190. # javascript_redirect_url = urlparse.urljoin(self.base_url, "/whalecom7cace3215643e22bb7b0b8cc97a7/whalecom0/InternalSite/RedirectToOrigURL.asp?site_name=public&secure=1")
  191. # javascript_redirect_request = urllib2.Request(javascript_redirect_url)
  192. # javascript_redirect_request.add_header('Referer', validate_url)
  193. # cookie_jar.add_cookie_header(javascript_redirect_request)
  194. # javascript_redirect_response = urllib2.urlopen(javascript_redirect_request)
  195. # return javascript_redirect_response
  196. # Wychavon is rather different, and will need some thought. There is no
  197. # advanced search page
  198. class NewForestDCParser(AcolnetParser):
  199. def _getCouncilReference(self, app_table):
  200. return app_table.findAll("a")[1].string.strip()
  201. class NewForestNPAParser(AcolnetParser):
  202. def _getCouncilReference(self, app_table):
  203. return app_table.findAll("a")[1].string.strip()
  204. class BoltonParser(AcolnetParser):
  205. def _getCouncilReference(self, app_table):
  206. return app_table.findAll("a")[1].string.strip()
  207. class LewishamParser(AcolnetParser):
  208. def _getCouncilReference(self, app_table):
  209. return app_table.findAll("a")[1].string.strip()
  210. if __name__ == '__main__':
  211. day = 22
  212. month = 1
  213. year = 2008
  214. #parser = AcolnetParser("Babergh", "Babergh", "http://planning.babergh.gov.uk/dcdatav2//acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  215. #parser = AcolnetParser("Basingstoke", "Basingstoke", "http://planning.basingstoke.gov.uk/DCOnline2/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  216. #parser = BassetlawParser("Bassetlaw", "Bassetlaw", "http://www.bassetlaw.gov.uk/planning/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  217. #parser = BoltonParser("Bolton", "Bolton", "http://www.planning.bolton.gov.uk/PlanningSearch/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  218. #parser = BridgnorthParser("Bridgnorth", "Bridgnorth", "http://www2.bridgnorth-dc.gov.uk/planning/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.PgeSearch")
  219. #parser = AcolnetParser("Bury", "Bury", "http://e-planning.bury.gov.uk/DCWebPages/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  220. #parser = CanterburyParser("Canterbury", "Canterbury", "http://planning.canterbury.gov.uk/scripts/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  221. #parser = AcolnetParser("Carlisle", "Carlisle", "http://planning.carlisle.gov.uk/acolnet/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  222. #parser = AcolnetParser("Croydon", "Croydon", "http://planning.croydon.gov.uk/DCWebPages/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  223. #parser = AcolnetParser("Derby", "Derby", "http://eplanning.derby.gov.uk/acolnet/planningpages02/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  224. #parser = AcolnetParser("East Lindsey", "East Lindsey", "http://www.e-lindsey.gov.uk/planning/AcolnetCGI.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch", "AcolnetParser")
  225. #parser = AcolnetParser("Exeter City Council", "Exeter", "http://pub.exeter.gov.uk/scripts/Acolnet/dataonlineplanning/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  226. #parser = AcolnetParser("Fylde", "Fylde", "http://www2.fylde.gov.uk/planning/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  227. #parser = AcolnetParser("Guildford", "Guildford", "http://www.guildford.gov.uk/DLDC_Version_2/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  228. #parser = AcolnetParser("Harlow", "Harlow", "http://planning.harlow.gov.uk/PlanningSearch/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  229. #parser = AcolnetParser("Havant", "Havant", "http://www3.havant.gov.uk/scripts/planningpages/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  230. #parser = AcolnetParser("Hertsmere", "Hertsmere", "http://www2.hertsmere.gov.uk/ACOLNET/DCOnline//acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  231. parser = LewishamParser("Lewisham", "Lewisham", "http://acolnet.lewisham.gov.uk/lewis-xslpagesdc/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.PgeSearch")
  232. #parser = AcolnetParser("Mid Suffolk", "Mid Suffolk", "http://planning.midsuffolk.gov.uk/planning/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  233. #parser = NewForestDCParser("New Forest District Council", "New Forest DC", "http://web3.newforest.gov.uk/planningonline/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  234. #parser = NewForestNPAParser("New Forest National Park Authority", "New Forest NPA", "http://web01.newforestnpa.gov.uk/planningpages/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  235. #parser = AcolnetParser("North Hertfordshire", "North Herts", "http://www.north-herts.gov.uk/dcdataonline/Pages/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.PgeSearch")
  236. #parser = AcolnetParser("North Wiltshire", "North Wilts", "http://planning.northwilts.gov.uk/DCOnline/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  237. #parser = OldhamParser("Oldham", "Oldham", "http://planning.oldham.gov.uk/planning/AcolNetCGI.gov?ACTION=UNWRAP&Root=PgeSearch")
  238. #parser = AcolnetParser("Renfrewshire", "Renfrewshire", "http://planning.renfrewshire.gov.uk/acolnetDCpages/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.PgeSearch")
  239. #parser = AcolnetParser("South Bedfordshire", "South Bedfordshire", "http://planning.southbeds.gov.uk/plantech/DCWebPages/acolnetcgi.exe?ACTION=UNWRAP&RIPNAME=Root.PgeSearch")
  240. #parser = SouthwarkParser("London Borough of Southwark", "Southwark", "http://planningonline.southwarksites.com/planningonline2/AcolNetCGI.exe?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  241. #parser = AcolnetParser("Suffolk Coastal", "Suffolk Coastal", "http://apps3.suffolkcoastal.gov.uk/DCDataV2/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  242. #parser = AcolnetParser("Surrey Heath", "Surrey Heath", "https://www.public.surreyheath-online.gov.uk/whalecom60b1ef305f59f921/whalecom0/Scripts/PlanningPagesOnline/acolnetcgi.gov?ACTION=UNWRAP&RIPNAME=Root.pgesearch")
  243. print parser.getResults(day, month, year)