Automatically exported from code.google.com/p/planningalerts
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

200 righe
8.4 KiB

  1. import urllib2
  2. import urllib
  3. import urlparse
  4. import datetime, time
  5. import cookielib
  6. cookie_jar = cookielib.CookieJar()
  7. from BeautifulSoup import BeautifulSoup
  8. from PlanningUtils import PlanningApplication, \
  9. PlanningAuthorityResults, \
  10. getPostcodeFromText
  11. search_date_format = "%d-%m-%Y" # Format used for the accepted date when searching
  12. possible_date_formats = [search_date_format, "%d/%m/%Y"]
  13. class CookieAddingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
  14. """The standard python HttpRedirectHandler doesn't add a cookie to the new request after a 302. This handler does."""
  15. def redirect_request(self, req, fp, code, msg, headers, newurl):
  16. new_request = urllib2.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, newurl)
  17. # We need to add a cookie from the cookie_jar
  18. cookie_jar.add_cookie_header(new_request)
  19. return new_request
  20. cookie_handling_opener = urllib2.build_opener(CookieAddingHTTPRedirectHandler())
  21. class OcellaParser:
  22. received_date_format = search_date_format
  23. def __init__(self,
  24. authority_name,
  25. authority_short_name,
  26. base_url,
  27. debug=False):
  28. self.authority_name = authority_name
  29. self.authority_short_name = authority_short_name
  30. self.base_url = base_url
  31. self.debug = debug
  32. self._results = PlanningAuthorityResults(self.authority_name, self.authority_short_name)
  33. # These will be used to store the column numbers of the appropriate items in the results table
  34. self.reference_col = None
  35. self.address_col = None
  36. self.description_col = None
  37. self.received_date_col = None
  38. self.accepted_date_col = None
  39. def getResultsByDayMonthYear(self, day, month, year):
  40. search_date = datetime.date(year, month, day)
  41. # First get the search page
  42. get_request = urllib2.Request(self.base_url)
  43. get_response = urllib2.urlopen(get_request)
  44. cookie_jar.extract_cookies(get_response, get_request)
  45. get_soup = BeautifulSoup(get_response.read())
  46. # We need to find where the post action goes
  47. action = get_soup.form['action']
  48. session_id = get_soup.find('input', {'name': 'p_session_id'})['value']
  49. # # From Breckland
  50. # p_object_name=FRM_WEEKLY_LIST.DEFAULT.SUBMIT_TOP.01
  51. # p_instance=1
  52. # p_event_type=ON_CLICK
  53. # p_user_args=
  54. # p_session_id=53573
  55. # p_page_url=http%3A%2F%2Fwplan01.intranet.breckland.gov.uk%3A7778%2Fportal%2Fpage%3F_pageid%3D33%2C30988%26_dad%3Dportal%26_schema%3DPORTAL
  56. # FRM_WEEKLY_LIST.DEFAULT.START_DATE.01=02-06-2008
  57. # FRM_WEEKLY_LIST.DEFAULT.END_DATE.01=09-06-2008
  58. # FRM_WEEKLY_LIST.DEFAULT.PARISH.01=
  59. post_data = urllib.urlencode(
  60. [('p_object_name', 'FRM_WEEKLY_LIST.DEFAULT.SUBMIT_TOP.01'),
  61. ('p_instance', '1'),
  62. ('p_event_type', 'ON_CLICK'),
  63. ('p_user_args', ''),
  64. ('p_session_id', session_id),
  65. ('p_page_url', self.base_url),
  66. ('FRM_WEEKLY_LIST.DEFAULT.START_DATE.01', search_date.strftime(search_date_format)),
  67. ('FRM_WEEKLY_LIST.DEFAULT.END_DATE.01', search_date.strftime(search_date_format)),
  68. ('FRM_WEEKLY_LIST.DEFAULT.PARISH.01', ''),
  69. ]
  70. )
  71. post_request = urllib2.Request(action, post_data)
  72. cookie_jar.add_cookie_header(post_request)
  73. post_request.add_header('Referer', self.base_url)
  74. post_response = cookie_handling_opener.open(post_request)
  75. post_soup = BeautifulSoup(post_response.read())
  76. results_table = post_soup.find("table", summary="Printing Table Headers")
  77. trs = results_table.findAll("tr")
  78. # We'll use the headings in the first tr to find out what columns the address, description, etc are in.
  79. ths = trs[0].findAll("th")
  80. th_index = 0
  81. for th in ths:
  82. th_content = th.font.string.strip()
  83. if th_content == 'Reference' or th_content == 'Application Ref':
  84. self.reference_col = th_index
  85. elif th_content == 'Location':
  86. self.address_col = th_index
  87. elif th_content == 'Proposal':
  88. self.description_col = th_index
  89. elif th_content == 'Development Description':
  90. self.description_col = th_index
  91. elif th_content == 'Received Date' or th_content == 'Date Received':
  92. self.received_date_col = th_index
  93. elif th_content == 'Accepted Date':
  94. self.accepted_date_col = th_index
  95. th_index += 1
  96. # If there is a received date, we'll use that, otherwise, we'll have to settle for the accepted date.
  97. self.received_date_col = self.received_date_col or self.accepted_date_col
  98. # We want all the trs except the first one, which is just headers,
  99. # and the last, which is empty
  100. trs = trs[1:-1]
  101. for tr in trs:
  102. self._current_application = PlanningApplication()
  103. tds = tr.findAll("td")
  104. self._current_application.council_reference = (tds[self.reference_col].font.a or tds[self.reference_col].a.font).string.strip()
  105. date_string = tds[self.received_date_col]
  106. for possible_format in possible_date_formats:
  107. try:
  108. self._current_application.date_received = datetime.datetime(*(time.strptime(tds[self.received_date_col].font.string.strip(), possible_format)[0:6]))
  109. except ValueError:
  110. pass
  111. self._current_application.address = tds[self.address_col].font.string.strip()
  112. self._current_application.postcode = getPostcodeFromText(self._current_application.address)
  113. self._current_application.description = tds[self.description_col].font.string.strip()
  114. self._current_application.info_url = tds[self.reference_col].a['href']
  115. # This is what a comment url looks like
  116. # It seems to be no problem to remove the sessionid (which is in any case blank...)
  117. # I can't see a good way to avoid having to go to the info page to find the moduleid though.
  118. #http://wplan01.intranet.breckland.gov.uk:7778/pls/portal/PORTAL.wwa_app_module.link?p_arg_names=_moduleid&p_arg_values=8941787057&p_arg_names=_sessionid&p_arg_values=&p_arg_names=APPLICATION_REFERENCE&p_arg_values=3PL%2F2008%2F0877%2FF
  119. # For the moment, we'll just use the info url, as that seems to work.
  120. self._current_application.comment_url = self._current_application.info_url
  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. if __name__ == '__main__':
  126. # parser = OcellaParser("Arun", "Arun", "http://www.arun.gov.uk/iplanning/portal/page?_pageid=33,4139&_dad=portal&_schema=PORTAL")
  127. # parser = OcellaParser("Breckland Council", "Breckland", "http://wplan01.intranet.breckland.gov.uk:7778/portal/page?_pageid=33,30988&_dad=portal&_schema=PORTAL")
  128. # parser = OcellaParser("Ellesmere Port", "Ellesmere Port", "http://ocella.epnbc.gov.uk/portal/page?_pageid=33,38205&_dad=portal&_schema=PORTAL")
  129. # parser = OcellaParser("Uttlesford", "Uttlesford", "http://planning.uttlesford.gov.uk/portal/page?_pageid=33,35447&_dad=portal&_schema=PORTAL")
  130. # parser = OcellaParser("North East Lincolnshire", "North East Lincolnshire", "http://planning.nelincs.gov.uk/portal/page?_pageid=33,68034&_dad=portal&_schema=PORTAL")
  131. # parser = OcellaParser("Fareham", "Fareham", "http://eocella.fareham.gov.uk/portal/page?_pageid=33,31754&_dad=portal&_schema=PORTAL")
  132. # parser = OcellaParser("Hillingdon", "Hillingdon", "http://w09.hillingdon.gov.uk/portal/page?_pageid=33,82093&_dad=portal&_schema=PORTAL")
  133. # Bad status line?
  134. # parser = BrecklandParser("Bridgend", "Bridgend", "http://eplan.bridgend.gov.uk:7778/portal/page?_pageid=55,31779&_dad=portal&_schema=PORTAL")
  135. # parser = ArunParser("Havering", "Havering", "http://planning.havering.gov.uk/portal/page?_pageid=33,1026&_dad=portal&_schema=PORTAL")
  136. # Can't find the URL similar to the others, even though it is clearly Ocella
  137. parser = OcellaParser("Great Yarmouth", "Great Yarmouth", "http://www.great-yarmouth.gov.uk/wmplan_application_search-6.htm")
  138. print parser.getResults(21,5,2008)
  139. #TODO
  140. # 1) Sort out proper comment url?
  141. # 2) Check for pagination
  142. # 3) Check no results case