这篇文章是在利用Python下载Landsat数据_孤城_001的博客-CSDN博客_python下载landsat的基础上完成的,但是可能因为种种原因,目前它的方法已经不能使用,需要修改安装包中的部分语句。
1,首先安装第三方包
pip install landsatxplore
2,修改包的内容
修改下面的函数,在EarthExplorer.py文件中。我主要删除了所有与 ncform 相关的东西,因为目前EarthExplorer删除了该部分内容。下面的代码,直接替换原来的文件就行。
class EarthExplorer(object):
"""Access Earth Explorer portal."""
def __init__(self, username, password):
"""Access Earth Explorer portal."""
self.session = requests.Session()
self.login(username, password)
self.api = API(username, password)
def logged_in(self):
"""Check if the log-in has been successfull based on session cookies."""
eros_sso = self.session.cookies.get("EROS_SSO_production_secure")
return bool(eros_sso)
def login(self, username, password):
"""Login to Earth Explorer."""
rsp = self.session.get(EE_LOGIN_URL)
csrf = _get_tokens(rsp.text)
payload = {
"username": username,
"password": password,
"csrf": csrf,
}
rsp = self.session.post(EE_LOGIN_URL, data=payload, allow_redirects=True)
if not self.logged_in():
raise EarthExplorerError("EE: login failed.")
def logout(self):
"""Log out from Earth Explorer."""
self.session.get(EE_LOGOUT_URL)
def _download(self, url, output_dir, timeout, chunk_size=1024, skip=False):
"""Download remote file given its URL."""
# Check availability of the requested product
# EarthExplorer should respond with JSON
with self.session.get(
url, allow_redirects=False, stream=True, timeout=timeout
) as r:
r.raise_for_status()
error_msg = r.json().get("errorMessage")
if error_msg:
raise EarthExplorerError(error_msg)
download_url = r.json().get("url")
try:
with self.session.get(
download_url, stream=True, allow_redirects=True, timeout=timeout
) as r:
file_size = int(r.headers.get("Content-Length"))
with tqdm(
total=file_size, unit_scale=True, unit="B", unit_divisor=1024
) as pbar:
local_filename = r.headers["Content-Disposition"].split("=")[-1]
local_filename = local_filename.replace('"', "")
local_filename = os.path.join(output_dir, local_filename)
if skip:
return local_filename
with open(local_filename, "wb") as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
pbar.update(chunk_size)
except requests.exceptions.Timeout:
raise EarthExplorerError(
"Connection timeout after {} seconds.".format(timeout)
)
return local_filename
def download(self, identifier, output_dir, dataset=None, timeout=300, skip=False):
"""Download a Landsat scene.
Parameters
----------
identifier : str
Scene Entity ID or Display ID.
output_dir : str
Output directory. Automatically created if it does not exist.
dataset : str, optional
Dataset name. If not provided, automatically guessed from scene id.
timeout : int, optional
Connection timeout in seconds.
skip : bool, optional
Skip download, only returns the remote filename.
Returns
-------
filename : str
Path to downloaded file.
"""
os.makedirs(output_dir, exist_ok=True)
if not dataset:
dataset = guess_dataset(identifier)
if is_display_id(identifier):
entity_id = self.api.get_entity_id(identifier, dataset)
else:
entity_id = identifier
url = EE_DOWNLOAD_URL.format(
data_product_id=DATA_PRODUCTS[dataset], entity_id=entity_id
)
filename = self._download(url, output_dir, timeout=timeout, skip=skip)
return filename
3 可以下载了,下面的代码几乎是抄的,我只是稍加注释和修改,稍作说明
import landsatxplore.api
from landsatxplore.earthexplorer import EarthExplorer
def request_Landsat(username,password,product,lat,lon,start_date,end_date,cloud_max):
api = landsatxplore.api.API(username, password)
scenes = api.search(
dataset=product,
latitude=lat,
longitude=lon,
start_date=start_date,
end_date=end_date,
max_cloud_cover=cloud_max)
print('{} scenes found.'.format(len(scenes)))
api.logout()
return scenes
def download_landsat(username,password,Landsat_name,output_dir):
Earth_Down = EarthExplorer(username, password)
for scene in Landsat_name:
# 下面代码将'entityId'改为'display_id',因为两个id下载名称有差别:
# 'entity_id': 'LC81960462015361LGN01',
# 'display_id': 'LC08_L1TP_196046_20151227_20170331_01_T1'
ID = scene['display_id']
print('Downloading data %s '% ID)
# 下面这行代码将原来的scene_id 改为identifier,因为scene_id已被弃用
Earth_Down.download(identifier=ID, output_dir=output_dir)
Earth_Down.logout()
if __name__ == '__main__':
username = ''
password = ''
#下面所有6行代码,可以建立任意循环,以达到批量下载的目的,不赘述
product = 'LANDSAT_8_C1'
lat = 19.53
lon = -1.53
start_date='2014-01-01'
end_date='2016-01-01'
cloud_max = 10
output_dir = 'G:\\aa\data'
Landsat_name = request_Landsat(username,password,product,lat,lon,start_date,end_date,cloud_max)
print(Landsat_name)
download_landsat(username,password,Landsat_name,output_dir)
4 尝试了一下,速度喜人