waratah_wynyard.rb 7.7 KB

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