请求是一个非常好的库.我想用它来下载大文件(> 1GB).问题是不可能将整个文件保存在内存中我需要以块的形式读取它.这是以下代码的问题
import requests
def DownloadFile(url)
local_filename = url.split('/')[-1]
r = requests.get(url)
f = open(local_filename, 'wb')
for chunk in r.iter_content(chunk_size=512 * 1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.close()
return
Run Code Online (Sandbox Code Playgroud)
由于某种原因它不起作用.在将其保存到文件之前,它仍会将响应加载到内存中.
UPDATE
如果你需要一个可以从FTP下载大文件的小客户端(Python 2.x /3.x),你可以在这里找到它.它支持多线程和重新连接(它确实监视连接),它还为下载任务调整套接字参数.
我是Python的新手,我一直在浏览本网站上的问答,以回答我的问题.但是,我是初学者,我发现很难理解一些解决方案.我需要一个非常基本的解决方案
有人可以向我解释一个简单的解决方案:"通过http下载文件"和"将其保存到Windows中的磁盘"吗?
我也不确定如何使用shutil和os模块.
我想下载的文件不到500 MB,是一个.gz存档文件.如果有人可以解释如何提取存档并利用其中的文件,那就太棒了!
这是一个部分解决方案,我从各种答案中总结出来:
import requests
import os
import shutil
global dump
def download_file():
global dump
url = "http://randomsite.com/file.gz"
file = requests.get(url, stream=True)
dump = file.raw
def save_file():
global dump
location = os.path.abspath("D:\folder\file.gz")
with open("file.gz", 'wb') as location:
shutil.copyfileobj(dump, location)
del dump
Run Code Online (Sandbox Code Playgroud)
有人可以指出错误(初学者级别)并解释任何更简单的方法来做到这一点?
谢谢!
如果在浏览器中点击以下 url,将下载 docx 文件我想用 python 自动下载。
我已经尝试过以下
from docx import Document
import requests
import json
from bs4 import BeautifulSoup
dwnurl = 'https://hudoc.echr.coe.int/app/conversion/docx/?library=ECHR&id=001-176931&filename=CASE%20OF%20NDIDI%20v.%20THE%20UNITED%20KINGDOM.docx&logEvent=False'
doc = requests.get(dwnurl)
print(doc.content) #printing the document like b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x00!\xfb\x16\x01\x16\x02\x00\x00\xec\x0c\x00\x00\x13\x00\xc4\x01[Content_Types].xml \xa2\xc0\
print(doc.raw) #printing the document like <urllib3.response.HTTPResponse object at 0x063D8BD0>
document = Document(doc.content)
document.save('test.docx')
#on document.save i have facing these issues
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "scraping_hudoc.py", line 40, in <module>
document = Document(doc.content)
File "C:\Users\204387\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\api.py", line 25, in Document
document_part = Package.open(docx).main_document_part
File "C:\Users\204387\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\opc\package.py", line …