download_nc.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import pandas as pd
  2. import requests
  3. import shutil
  4. import time
  5. import os
  6. from datetime import date
  7. from selenium.webdriver import Firefox
  8. from selenium.webdriver.firefox.options import Options
  9. from random import randrange
  10. from pathlib import Path
  11. root = Path(__file__).parents[2]
  12. """
  13. based on download_bur from national-inventory-submissions
  14. # (https://github.com/openclimatedata/national-inventory-submisions)
  15. """
  16. ###############
  17. #
  18. # TODO
  19. # download directly via selenium see link below
  20. # https://sqa.stackexchange.com/questions/2197/
  21. # how-to-download-a-file-using-seleniums-webdriver
  22. # for automatic downloading see https://stackoverflow.com/questions/70740163/
  23. # python-selenium-firefox-driver-dismiss-open-save-file-popup
  24. ###############
  25. submissions = pd.read_csv(root / "downloaded_data" / "UNFCCC" /
  26. "submissions-nc.csv")
  27. url = "https://unfccc.int/non-annex-I-NCs"
  28. # if we get files of this size they are error pages and we need to
  29. # try the download again
  30. error_file_sizes = [212, 210]
  31. # Ensure download path and subfolders exist
  32. download_path = root / "downloaded_data" / "UNFCCC"
  33. if not download_path.exists():
  34. download_path.mkdir(parents=True)
  35. # set options for headless mode
  36. profile_path = ".firefox"
  37. options = Options()
  38. #options.add_argument('-headless')
  39. # create profile for headless mode and automatic downloading
  40. options.set_preference('profile', profile_path)
  41. options.set_preference('browser.download.folderList', 2)
  42. # set up selenium driver
  43. driver = Firefox(options=options)
  44. # visit the main data page once to create cookies
  45. driver.get(url)
  46. time.sleep(20)
  47. # get the session id cookie
  48. cookies_selenium = driver.get_cookies()
  49. cookies = {}
  50. for cookie in cookies_selenium:
  51. cookies[cookie['name']] = cookie['value']
  52. print(cookies)
  53. new_downloaded = []
  54. for idx, submission in submissions.iterrows():
  55. print("=" * 60)
  56. bur = submission.Kind
  57. title = submission.Title
  58. url = submission.URL
  59. country = submission.Country
  60. country = country.replace(' ', '_')
  61. print(title)
  62. country_folder = download_path / country
  63. if not country_folder.exists():
  64. country_folder.mkdir()
  65. local_filename = country_folder / bur / url.split('/')[-1]
  66. local_filename_underscore = \
  67. download_path / country / bur / \
  68. url.split('/')[-1].replace("%20", "_").replace(" ", "_")
  69. if not local_filename.parent.exists():
  70. local_filename.parent.mkdir()
  71. ### remove, not needed as no legacy data present
  72. #if local_filename.exists():
  73. # # rename
  74. # local_filename.rename(local_filename_underscore)
  75. # print("Renamed " + bur + "/" + country + "/" + local_filename.name)
  76. # this should never be needed but in case anything goes wrong and
  77. # an error page is present it should be overwritten
  78. if local_filename_underscore.exists():
  79. # check file size. if 210 or 212 bytes it's the error page
  80. if Path(local_filename_underscore).stat().st_size in error_file_sizes:
  81. # found the error page. delete file
  82. os.remove(local_filename_underscore)
  83. # now we have remove error pages, so a present file should not be overwritten
  84. if not local_filename_underscore.exists():
  85. i = 0 # reset counter
  86. while not local_filename_underscore.exists() and i < 10:
  87. # for i = 0 and i = 5 try to get a new session ID
  88. if i == 1 or i == 5:
  89. driver = webdriver.Firefox(options=options,
  90. firefox_profile=profile)
  91. # visit the main data page once to create cookies
  92. driver.get(url)
  93. time.sleep(20)
  94. # get the session id cookie
  95. cookies_selenium = driver.get_cookies()
  96. cookies = {}
  97. for cookie in cookies_selenium:
  98. cookies[cookie['name']] = cookie['value']
  99. r = requests.get(url, stream=True, cookies=cookies)
  100. with open(str(local_filename_underscore), 'wb') as f:
  101. shutil.copyfileobj(r.raw, f)
  102. # check file size. if 210 or 212 bytes it's the error page
  103. if Path(local_filename_underscore).stat().st_size in error_file_sizes:
  104. # found the error page. delete file
  105. os.remove(local_filename_underscore)
  106. # sleep a bit to avoid running into captchas
  107. time.sleep(randrange(5, 15))
  108. if local_filename_underscore.exists():
  109. new_downloaded.append(submission)
  110. print("Download => downloaded_data/UNFCCC/" + country + "/" + bur +
  111. "/" + local_filename_underscore.name)
  112. else:
  113. print("Failed downloading downloaded_data/UNFCCC/" + country + "/"
  114. + bur + "/" + local_filename_underscore.name)
  115. else:
  116. print("=> Already downloaded " + local_filename_underscore.name)
  117. driver.close()
  118. df = pd.DataFrame(new_downloaded)
  119. df.to_csv(download_path / "00_new_downloads_nc-{}.csv".format(date.today()), index=False)