waratah_wynyard.rb 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Waratah–Wynyard Council — Advertised / Planning Applications
  2. require "nokogiri"
  3. require "uri"
  4. require "cgi"
  5. require_relative "../lib/enrich"
  6. require_relative "../lib/log"
  7. TABLE = ENV.fetch("TABLE_NAME") # da_waratah_wynyard
  8. URL = "https://www.warwyn.tas.gov.au/planning-and-development/advertised-permits/"
  9. DB.ensure_table!(TABLE)
  10. def abs_url(base, href)
  11. return "" if href.to_s.strip.empty?
  12. URI.join(base, href).to_s
  13. rescue URI::InvalidURIError
  14. href.to_s
  15. end
  16. # DA 2025/0123, DA2025-0123, DA 114-2025 etc.
  17. REF_RX1 = %r{\bDA\s*(20\d{2})\s*/\s*([A-Za-z0-9\-\._]+)}i
  18. REF_RX2 = %r{\bDA(20\d{2})\s*[-\/]?\s*([0-9]{3,})\b}i
  19. REF_RX3 = %r{\bDA\s*([0-9]{1,4})\s*-\s*(20\d{2})\b}i
  20. def extract_ref(str)
  21. s = CGI.unescape(str.to_s)
  22. if (m = s.match(REF_RX1)) then return "DA #{m[1]} / #{m[2]}" end
  23. if (m = s.match(REF_RX2)) then return "DA #{m[1]} / #{m[2]}" end
  24. if (m = s.match(REF_RX3)) then return "DA #{m[2]} / #{m[1]}" end
  25. nil
  26. end
  27. def extract_date_like(str)
  28. s = str.to_s
  29. return $1 if s =~ /(\b\d{1,2}\/\d{1,2}\/\d{2,4}\b)/
  30. return $1 if s =~ /(\b\d{1,2}\s+[A-Za-z]{3,}\s+\d{4}\b)/
  31. return $1 if s =~ /(\b[A-Za-z]{3,}\s+\d{1,2},?\s+\d{4}\b)/
  32. ""
  33. end
  34. def extract_on_notice_raw(text)
  35. s = text.to_s.gsub(/\s+/, " ")
  36. if s =~ /\bon\s*notice\s*(until|to)\s*[:\-]?\s*([A-Za-z0-9\/ ,]+)/i
  37. d = extract_date_like($2); return d unless d.empty?
  38. end
  39. if s =~ /clos(?:e|ing|es)\s*(on)?\s*[:\-]?\s*([A-Za-z0-9\/ ,]+)/i
  40. d = extract_date_like($2); return d unless d.empty?
  41. end
  42. if s =~ /submissions?\s*close\s*[:\-]?\s*([A-Za-z0-9\/ ,]+)/i
  43. d = extract_date_like($1); return d unless d.empty?
  44. end
  45. extract_date_like(s)
  46. end
  47. def nearest_context_text(a)
  48. host = a.ancestors("li, p, div, tr, article").first || a.parent
  49. host ? host.text.to_s.strip.gsub(/\s+/, " ") : ""
  50. end
  51. def parse_list_items(doc, base_url)
  52. rows = []
  53. anchors = doc.css("a").select { |a|
  54. href = a["href"].to_s
  55. a.text.to_s.strip.match?(/application|permit|planning|advertis/i) || href.downcase.end_with?(".pdf")
  56. }
  57. anchors.each do |a|
  58. href = a["href"].to_s
  59. link_text = a.text.to_s.strip
  60. document_url = abs_url(base_url, href)
  61. ctx = nearest_context_text(a)
  62. title_reference = link_text.empty? ? ctx[0,200] : link_text
  63. text_for_parse = [link_text, ctx].reject(&:empty?).uniq.join(" — ")
  64. # Address guess
  65. address = link_text.length >= 6 ? link_text : ctx[0, 140]
  66. ref = extract_ref(text_for_parse) || extract_ref(File.basename(document_url))
  67. on_raw = extract_on_notice_raw(text_for_parse)
  68. on_dt = Util.parse_aus_date(on_raw)
  69. description = if text_for_parse =~ /proposal\s*[:\-]\s*([^—\-]+)\b/i
  70. $1.strip
  71. else
  72. "Development Application"
  73. end
  74. next if ref.nil? || address.to_s.strip.empty?
  75. rows << {
  76. council_reference: ref,
  77. address: address.to_s.strip,
  78. description: description,
  79. date_received: on_dt,
  80. date_received_raw: on_raw,
  81. document_url: document_url,
  82. title_reference: title_reference
  83. }
  84. end
  85. rows.uniq { |r| [r[:council_reference], r[:address]] }
  86. end
  87. def parse_detail_page(url)
  88. html = Http.get(url)
  89. doc = Nokogiri::HTML(html)
  90. # Try simple two-column tables first
  91. kv = {}
  92. doc.css("table tr").each do |tr|
  93. cells = tr.css("th, td")
  94. next unless cells.length >= 2
  95. key = cells[0].text.strip
  96. val = cells[1].text.strip
  97. kv[key] = val unless key.empty?
  98. end
  99. if kv.any?
  100. find = ->(rx) { kv.find { |k, _| k =~ rx }&.last.to_s.strip }
  101. council_reference = find.call(/(Application\s*(No|Number|ID)|Reference)/i)
  102. address = find.call(/(Address|Location|Property)/i)
  103. description = find.call(/(Proposal|Description)/i)
  104. on_notice_raw = find.call(/(On\s*Notice\s*(until|to)|Closing\s*Date|Closes|Submissions)/i)
  105. pdf = doc.at_css("a[href$='.pdf'], a[href*='.pdf?']")&.[]("href")
  106. document_url = pdf ? abs_url(url, pdf) : ""
  107. unless council_reference.empty? || address.empty?
  108. return {
  109. council_reference: council_reference,
  110. address: address,
  111. description: description.empty? ? "Development Application" : description,
  112. date_received_raw: on_notice_raw,
  113. date_received: Util.parse_aus_date(on_notice_raw),
  114. document_url: document_url,
  115. title_reference: doc.at_css("h1, .entry-title")&.text&.strip.to_s
  116. }
  117. end
  118. end
  119. # Fallback: parse from page text
  120. page_text = doc.text.to_s.strip.gsub(/\s+/, " ")
  121. ref = extract_ref(page_text)
  122. on_raw = extract_on_notice_raw(page_text)
  123. on_dt = Util.parse_aus_date(on_raw)
  124. h1 = doc.at_css("h1, .entry-title")&.text&.strip.to_s
  125. address = h1.empty? ? page_text[0, 140] : h1
  126. pdf = doc.at_css("a[href$='.pdf'], a[href*='.pdf?']")&.[]("href")
  127. document_url = pdf ? abs_url(url, pdf) : ""
  128. return nil if ref.nil? || address.empty?
  129. {
  130. council_reference: ref,
  131. address: address,
  132. description: "Development Application",
  133. date_received_raw: on_raw,
  134. date_received: on_dt,
  135. document_url: document_url,
  136. title_reference: h1
  137. }
  138. end
  139. begin
  140. html = URL.include?("/eservice/") ? Http.dorset_session_get(URL) : Http.get(URL)
  141. rescue StandardError => e
  142. Log.warn "scraper", "Failed to fetch #{URL}: #{e.class} #{e.message}"
  143. exit 1
  144. end
  145. doc = Nokogiri::HTML(html)
  146. host = begin
  147. URI.parse(URL).host
  148. rescue URI::InvalidURIError
  149. nil
  150. end
  151. anchors = doc.css("a").map { |a| abs_url(URL, a["href"].to_s) }.select { |u|
  152. next false if u.empty? || u.start_with?("#")
  153. u.downcase.end_with?(".pdf") || begin
  154. uh = URI.parse(u).host rescue nil
  155. host && uh == host
  156. end
  157. }.uniq
  158. rows = []
  159. anchors.each do |u|
  160. if u.downcase.end_with?(".pdf")
  161. if (a = doc.at_css(%Q{a[href="#{u}"]}))
  162. ctx_text = nearest_context_text(a)
  163. title = a.text.to_s.strip
  164. ref = extract_ref([title, ctx_text].join(" — "))
  165. addr = title.length >= 6 ? title : ctx_text[0, 140]
  166. on_raw = extract_on_notice_raw([title, ctx_text].join(" — "))
  167. on_dt = Util.parse_aus_date(on_raw)
  168. next if ref.nil? || addr.to_s.strip.empty?
  169. rows << {
  170. council_reference: ref,
  171. address: addr,
  172. description: "Development Application",
  173. date_received: on_dt,
  174. date_received_raw: on_raw,
  175. document_url: u,
  176. title_reference: title.empty? ? ctx_text[0,200] : title
  177. }
  178. end
  179. else
  180. begin
  181. item = parse_detail_page(u)
  182. rows << item if item
  183. rescue StandardError => e
  184. Log.warn "scraper", "Skip detail #{u}: #{e.class} #{e.message}"
  185. end
  186. end
  187. end
  188. # Safety net: scrape items from the main page content too
  189. rows += parse_list_items(doc, URL)
  190. rows.uniq! { |r| [r[:council_reference], r[:address]] }
  191. puts "Found #{rows.length} item(s) for #{TABLE}"
  192. rows.each do |r|
  193. cr = r[:council_reference].to_s
  194. addr = r[:address].to_s
  195. next if addr.strip.empty?
  196. next if addr =~ /\A(?:download|advertised planning applications)\z/i
  197. next if cr.strip.empty?
  198. next if addr == cr
  199. DB.upsert(TABLE, {
  200. description: r[:description],
  201. date_received: r[:date_received],
  202. date_received_raw: r[:date_received_raw],
  203. address: addr,
  204. council_reference: cr,
  205. applicant: "",
  206. owner: ""
  207. })
  208. enrich_after_upsert!(
  209. table: TABLE,
  210. council_reference: cr,
  211. address: addr
  212. )
  213. begin
  214. upd = DB.client.prepare(
  215. "UPDATE `#{DB.client.escape(TABLE)}` " \
  216. "SET document_url = ?, on_notice_to = ?, on_notice_to_raw = ?, title_reference = ? " \
  217. "WHERE council_reference = ? AND address = ?"
  218. )
  219. upd.execute(r[:document_url], r[:date_received], r[:date_received_raw], r[:title_reference], cr, addr)
  220. rescue StandardError => e
  221. Log.warn "scraper", "Extras update skipped for #{cr}: #{e.class} #{e.message}"
  222. end
  223. puts "Upserted #{cr} -> #{addr}"
  224. end
  225. puts "Done #{TABLE}."