I recently started writing Python for a project I am working on. I wrote a script that takes a list of URLs of images (like in a txt file) and downloads them all. However, some of the URLs on the list are old and do not work any more. This causes an error. In addition, if a link takes to long to load it will also cause an error.
Code: import urllib.request
import random
def downloadImageFromURL(url):
name = random.randrange(1, 10000)
full_name = str(name) + ".jpg"
urllib.request.urlretrieve(url, full_name)
f = open('url.txt','r')
for row in range(0, 10):
line = f.readline()
try:
downloadImageFromURL(line)
except ConnectionError:
print("Failed to open url.")
print(line)
f.close()
NEW CODE:
import urllib.request
import random
def sendRequest(url):
try:
page = requests.get(url, stream = True, timeout = 5)
except Exception:
return False
else:
if (page.status_code == 200):
return page
else:
return False
f = open('url.txt','r')
for row in range(0, 10):
line = f.readline()
try:
sendRequest(line)
except ConnectionError:
print("Failed to open url.")
print(line)
f.close()
Thank you!