python - 使用python从url下载多个压缩文件

标签 python url download

我正在尝试从网站下载多个压缩文件。我查看了下载一个文件的答案,看起来非常简单,但我在使其适用于多个文件时遇到了困难。该网址有超过 140 个我想要下载的压缩文件。

到目前为止我的代码想法是:

import urllib
url = "http://ftp.geogratis.gc.ca/pub/nrcan_rncan/vector/geobase_nhn_rhn/shp_en/03/"
##search url for zipped files and download them (this is where I am stuck)
urlfile = (the zipped files??)
if urlfile.endswith (".zip"):
   urllib.urlretrieve (url, r"C:\Users\maverick\Desktop\Canada Features")

我知道它甚至还没有接近我所需要的,但如果能朝正确的方向插入,我们将不胜感激。我也看过Scrapy,但我认为urlib应该能够完成任务。

最佳答案

正如 @Eric 所指出的,该服务器基本上是为 ftp 服务器运行 html 替代接口(interface)。您可以直接使用 ftp 接口(interface),例如:

from ftplib import FTP
import os

FTP_HOST = "ftp.geogratis.gc.ca"
FTP_DIR  = "pub/nrcan_rncan/vector/geobase_nhn_rhn/shp_en/03/"
OUT_DIR  = "/my/documents"    # <-- point this to an appropriate location!

# connect to host
ftp = FTP(FTP_HOST)
ftp.login()

# get list of .zip files
ftp.cwd(FTP_DIR)
files = ftp.nlst()
files = [f for f in files if f.lower().endswith(".zip")]

# download files
num = len(files)
for i, fname in enumerate(files, 1):
    print("Downloading {} ({}/{}) ... ".format(fname, i, num), end='')
    local_file = os.path.join(OUT_DIR, fname)
    with open(local_file, "wb") as outf:
        ftp.retrbinary("RETR "+fname, outf.write)
    print("done!")

ftp.close()

请注意,这可能需要一段时间;该目录包含 9.3 GB 的文件。

关于python - 使用python从url下载多个压缩文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44250963/

相关文章:

python - 日期时间模块中异常消息的来源。值错误: year 10000 is out of range

linux - 如何在不同的目录中包含相同的文件?

asp.net-mvc - MVC Controller.File 返回空白 pdf

python - 如何将 spark 数据帧保存到 HDFS 上的 csv?

python - PyAudio Input Overflowed -9981 - 没有有效的解决方案

python - 有没有办法在现有变量上使用 Pillows "Image.convert()"?

javascript - 如何使用 native Angular 代码解析外部链接 url?

python - Django:不推荐使用对 url() 的字符串 View 参数的支持,并将在 Django 1.10 中删除

java - 如何在 Java 中实现下载速率限制?

php - 在发送给用户之前重命名文件?