0

So guys, I have this file thay I need to download using python, and this is my code

import requests

url = "http://servicos.ibama.gov.br/ctf/publico/areasembargadas/downloadListaAreasEmbargadas.php"

response = requests.get(url)

url = open("test.zip", "wb+")
url.write(response.content)
url.close()

if you click into the link you'll see that it is a zipped file, that's why i put the .zip extension, it downloads the file but it is a file that can't be opened, I have a feeling that I am doing something wrong.

Also I tryied to change it to .txt so I could see the content of what it was downloading and I saw that it saves only the HTML code of the page that redirects me to the downloading URL, quite frankly I am as lost as one can be

  • Does this answer your question? [Download Returned Zip file from URL](https://stackoverflow.com/questions/9419162/download-returned-zip-file-from-url) – sahasrara62 Nov 26 '20 at 10:46

2 Answers2

0

As suggested in the ansyer of this post:

import requests 

def download_url(url, save_path, chunk_size=128):
    r = requests.get(url, stream=True)
    with open(save_path, 'wb') as fd:
        for chunk in r.iter_content(chunk_size=chunk_size):
            fd.write(chunk)

with save_path the location of where you want to save your file.

robinood
  • 121
  • 5
  • i did exactly this and the program runs, but when I go to the location i gave as path there is nothing there –  Nov 26 '20 at 12:56
  • Did you give an absolute path or a relative one? You can try to just use a filename (like "test.zip") and see if you can find the file "test.zip" at the same place you executed your code. If it is the case, then you are probably not looking at the rigth place when using your full save_path – robinood Nov 26 '20 at 13:07
0

Here is a one liner. Notice the b next to w for bytes.

from urllib.request import urlopen


open('Sample1.zip', 'wb').write(urlopen('http://servicos.ibama.gov.br/ctf/publico/areasembargadas/downloadListaAreasEmbargadas.php').read())
Abhishek Rai
  • 1,538
  • 2
  • 8
  • 21