我遇到了一个令人沮丧的问题,我不知道如何解决。我想测试该脚本以从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'
有人知道为什么会发生吗? 感谢您的答复
答案 0 :(得分:0)
这意味着requests
无法说出url中指定的协议,即FTP
。通常,它用于说HTTP
。
在URL(实际上是URI)中,scheme
指定用于对话框的协议。
在您的情况下为FTP
,因为URI的前缀为ftp://
请查看here,以详细了解构成URI的组件及其含义。
有一些特定的库可以“说” FTP(文件传输协议)
例如标准ftplib
但是如果您想/需要使用requests
,可以尝试使用requests-ftp。
如前所述,它为requests
库提供了FTP传输适配器。