首页 > 解决方案 > Python - 未找到连接适配器

问题描述

我有这个令人沮丧的问题,我不知道如何解决。我想测试该脚本以从 ftp 服务器下载一些东西:

import requests
import sys
import time

def downloadFile(url, directory) :
  localFilename = url.split('/')[-1]
  print(url)
  with open(directory + '/' + localFilename, 'wb') as f:
    start = time.clock()
    r = requests.get(url, stream=True)
    total_length = r.headers.get('content-length')
    dl = 0
    if total_length is None: # no content length header
      f.write(r.content)
    else:
      for chunk in r.iter_content(1024):
        dl += len(chunk)
        f.write(chunk)
        done = int(50 * dl / total_length)
        sys.stdout.write("\r[%s%s] %s bps" % ('=' * done, ' ' * (50-done), dl//(time.clock() - start)))
        print("")
  return (time.clock() - start)

def main() :
  if len(sys.argv) > 1 :
        url = sys.argv[1]
  else :
        url = input("Enter the URL : ")
  directory = input("Where would you want to save the file ?")

  time_elapsed = downloadFile(url, directory)
  print( "Download complete...")
  print ("Time Elapsed: " + time_elapsed)


if __name__ == "__main__" :
  main()

我使用的网址是ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/CHDI/CHR2010_051010.xlsx但是当我运行它时出现错误:

  File "C:\Users\Pigeon\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\sessions.py", line 731, in get_adapter
    raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/CHDI/CHR2010_051010.xlsx'

有谁知道为什么会这样?谢谢您的回复

标签: pythonpython-3.x

解决方案


这意味着requests没有办法说出url中指定的协议,即FTP。通常是用来说话的HTTP

在 URL(实际上是 URI)中,scheme指定了用于对话的协议。

在您的情况下,它FTP是 URI 的前缀所说的ftp://

请在此处查看构成 URI 的组件及其含义的详细分类。

有特定的库可以“说”FTP(文件传输协议)

例如标准的ftplib

但如果您想/需要使用requests,您可以尝试使用requests-ftp

正如它所说,它为requests库提供了一个 FTP 传输适配器。


推荐阅读