unfccc_submission_info.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # helper functions to gather submission info from UNFCCC website
  2. import time
  3. import re
  4. from random import randrange
  5. from typing import Dict, List
  6. from selenium.webdriver import Firefox
  7. from selenium.common.exceptions import WebDriverException
  8. from bs4 import BeautifulSoup
  9. def get_unfccc_submission_info(
  10. url: str,
  11. driver: Firefox,
  12. max_tries: int=10,
  13. ) -> List[Dict[str,str]]:
  14. info = []
  15. pattern = re.compile(r"BUR ?\d")
  16. i = 0
  17. while i < max_tries:
  18. try:
  19. driver.get(url)
  20. html = BeautifulSoup(driver.page_source, "html.parser")
  21. title = html.find("h1").contents[0]
  22. break
  23. except (AttributeError, WebDriverException):
  24. print(f"Error fetching {url}")
  25. print("Retrying ...")
  26. time.sleep(randrange(5, 15))
  27. i += 1
  28. continue
  29. if i == max_tries:
  30. print(f"Aborting after {max_tries} tries")
  31. else:
  32. match = pattern.search(title)
  33. if match:
  34. kind = match.group(0).replace(" ", "")
  35. else:
  36. kind = None
  37. h2 = html.find("h2", text="Versions")
  38. if h2:
  39. div = h2.findNext("div")
  40. links = div.findAll("a")
  41. try:
  42. country = (
  43. html.find("h2", text="Countries").findNext("div").findNext("div").text
  44. )
  45. except AttributeError:
  46. country = (
  47. html.find("h2", text="Corporate Author")
  48. .findNext("div")
  49. .findNext("div")
  50. .text
  51. )
  52. doctype = (
  53. html.find("h2", text="Document Type").findNext("div").findNext("div").text
  54. )
  55. for link in links:
  56. url = link.attrs["href"]
  57. if not kind:
  58. match = pattern.search(url.upper())
  59. if match:
  60. kind = match.group(0)
  61. else:
  62. if ("CRF" in doctype) or ("CRF" in title):
  63. kind = "CRF"
  64. elif ("SEF" in doctype) or ("SEF" in title):
  65. kind = "SEF"
  66. elif ("NIR" in doctype) or ("NIR" in title):
  67. kind = "NIR"
  68. elif "NC" in title:
  69. kind = "NC"
  70. elif "Status report" in title:
  71. kind = "CRF"
  72. else:
  73. kind = "other"
  74. info.append({
  75. "Kind": kind,
  76. "Country": country,
  77. "Title": title,
  78. "URL": url,
  79. })
  80. print("\t".join([kind, country, title, url]))
  81. else:
  82. print(f"No files found for {url}")
  83. return info