Skip to content

Commit 85cc5bc

Browse files
Merge pull request #3143 from Derderderr/patch-2
Update scrap_file.py
2 parents 9aa7cd7 + 0c2fcfa commit 85cc5bc

File tree

1 file changed

+14
-24
lines changed

1 file changed

+14
-24
lines changed

scrap_file.py

Lines changed: 14 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,23 @@
66
import requests
77

88

9-
# Function for download file parameter taking as url
10-
9+
def download(url, filename):
10+
try:
11+
with requests.get(url, stream=True, timeout=10) as response:
12+
response.raise_for_status() # Raises error for 4xx/5xx
1113

12-
def download(url):
13-
f = open(
14-
"file_name.jpg", "wb"
15-
) # opening file in write binary('wb') mode with file_name.ext ext=extension
16-
f.write(requests.get(url).content) # Writing File Content in file_name.jpg
17-
f.close()
18-
print("Succesfully Downloaded")
14+
with open(filename, "wb") as file:
15+
for chunk in response.iter_content(chunk_size=8192):
16+
if chunk:
17+
file.write(chunk)
1918

19+
print(f"Successfully downloaded: {filename}")
2020

21-
# Function is do same thing as method(download) do,but more strict
22-
def download_2(url):
23-
try:
24-
response = requests.get(url)
25-
except Exception:
26-
print("Failed Download!")
27-
else:
28-
if response.status_code == 200:
29-
with open("file_name.jpg", "wb") as f:
30-
f.write(requests.get(url).content)
31-
print("Succesfully Downloaded")
32-
else:
33-
print("Failed Download!")
21+
except requests.exceptions.RequestException as e:
22+
print(f"Download failed: {e}")
3423

3524

36-
url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4" # URL from which we want to download
25+
# Example usage
26+
url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4"
27+
download(url, "avatar.jpg")
3728

38-
download(url)

0 commit comments

Comments
 (0)