download_nc.py 4.8 KB

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