diff --git a/scrap_file.py b/scrap_file.py index 7655e792cbe..aab6e2a2e08 100644 --- a/scrap_file.py +++ b/scrap_file.py @@ -6,33 +6,23 @@ import requests -# Function for download file parameter taking as url - +def download(url, filename): + try: + with requests.get(url, stream=True, timeout=10) as response: + response.raise_for_status() # Raises error for 4xx/5xx -def download(url): - f = open( - "file_name.jpg", "wb" - ) # opening file in write binary('wb') mode with file_name.ext ext=extension - f.write(requests.get(url).content) # Writing File Content in file_name.jpg - f.close() - print("Succesfully Downloaded") + with open(filename, "wb") as file: + for chunk in response.iter_content(chunk_size=8192): + if chunk: + file.write(chunk) + print(f"Successfully downloaded: {filename}") -# Function is do same thing as method(download) do,but more strict -def download_2(url): - try: - response = requests.get(url) - except Exception: - print("Failed Download!") - else: - if response.status_code == 200: - with open("file_name.jpg", "wb") as f: - f.write(requests.get(url).content) - print("Succesfully Downloaded") - else: - print("Failed Download!") + except requests.exceptions.RequestException as e: + print(f"Download failed: {e}") -url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4" # URL from which we want to download +# Example usage +url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4" +download(url, "avatar.jpg") -download(url)