In "Download images from a specific URL in bulk with python" that I wrote as a modified version before, for example This time, I fixed the problem that the image could not be downloaded due to ERROR.
I was only judging if there was "../", but I added it because I wasn't thinking about when there was no domain. Judgment solved the problem by downloading as it is if there is "http: //" or "https: //", or by prefixing the URL that was entered first.
Before editing
for j in range(0,(len_url-1)):
url = number_url[j]
print (url)
if("../" in url):
root_url = get_url_root(serch_url)
if(root_url!=0):
url = url.replace("..",root_url)
print url
download(url)
else:
download(input_url + url)
After editing
for j in range(0,(len_url-1)):
url = number_url[j]
print (url)
if("../" in url):
root_url = get_url_root(serch_url)
if(root_url!=0):
url = url.replace("..",root_url)
print url
download(url)
elif("http://" in url):
download(url)
elif("https://" in url):
download(url)
else:
download(input_url + url)
get_image.py
# -*- coding: utf-8 -*-
import urllib
import urllib2
import os.path
import sys
from HTMLParser import HTMLParser
def download(url):
img = urllib.urlopen(url)
localfile = open(os.path.basename(url), 'wb')
localfile.write(img.read())
img.close()
localfile.close()
def get_url_root(url):
if("http://" in url):
url_delet_http = url.lstrip("http://")
if("/" in url_delet_http):
url_root = "http://" + url_delet_http[0:url_delet_http.find("/")]
return url_root
elif("https://" in url):
url_delet_http = url.lstrip("https://")
if("/" in url_delet_http):
url_root = "http://" + url_delet_http[0:url_delet_http.find("/")]
return url_root
return 0
class imgParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
def handle_starttag(self,tagname,attribute):
if tagname.lower() == "img":
for i in attribute:
if i[0].lower() == "src":
img_url=i[1]
#Creating a file that collects the URLs of the acquired photos
f = open("collection_url.txt","a")
f.write("%s\t"%img_url)
f.close()
if __name__ == "__main__":
print('Enter the URL of the site where you want to get the photo.')
input_url = raw_input('>>> ')
serch_url = input_url
htmldata = urllib2.urlopen(serch_url)
print('Currently getting image files...')
parser = imgParser()
parser.feed(htmldata.read())
parser.close()
htmldata.close()
#Read the generated file
f = open("collection_url.txt","r")
for row in f:
row_url = row.split('\t')
len_url = len(row_url)
f.close()
number_url = []
for i in range(0,(len_url-1)):
number_url.append(row_url[i])
for j in range(0,(len_url-1)):
url = number_url[j]
print (url)
if("../" in url):
root_url = get_url_root(serch_url)
if(root_url!=0):
url = url.replace("..",root_url)
print url
download(url)
elif("http://" in url):
download(url)
elif("https://" in url):
download(url)
else:
download(input_url + url)
print('The image download is complete.')
#Delete file
os.remove("collection_url.txt")
Recommended Posts