白猫学生のブログ

自分の趣味をひたすら投稿するブログ

Pythonで特定URLの画像を全部保存する方法

こんにちは.

今回はPythonで指定したURLのサイトの画像を全部保存していく方法を考えて見ました.(注意: Python2.7.3を使用しています.)

なぜ,このようなことを考えたかといいますと,ウェブ漫画を読んでいた時に

「この画像を一気に保存して読んだら楽なのでは?」

と突然思ってしまったからです.

実際作ってみた感想としましては,そのまま読んでも変わらないということですね...

消される可能性のある画像を一気に保存したい場合は使えると思います...

きっと...



では本題に入らさせてもらいますが,プログラムは以下の通りになります.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2
import urllib
import time
import sys

#初期設定
imageURL = []
alreadySaved = []
count = 0
debug_count = 0
total_count = 0
rate = 0.0

#URLの設定
url = "http://www.geocities.jp/cba4jp/jyu00000/jyu001-020/jyudo001-001.html"

#保存先の設定
savePath = "./Download/"	#フォルダをあらかじめ作成してください

#ソースコードを文字列として取得
try:
	fp = urllib2.urlopen(url)
	html = fp.read()
except:
	print("URL Error")
	time.sleep(1.5)
	sys.exit()

#画像URLを取得する関数
def getImageURL(place):
	global html
	global imageURL
	finishFlag = 0
	saveFlag = 0
	url_save = ""

	while finishFlag == 0:
		if html[place] == "\"":
			place += 1
			while saveFlag == 0:
				url_save += html[place]
				place += 1
				if html[place] == "\"":
					saveFlag = 1
					finishFlag = 1

		else:
			place += 1

	imageURL.append(url_save)
	return place

#画像URLから画像を保存
def download(downloadURL, count):
        global savePath
	global url

	urlFlag = 0
	download_count = 0

	try:
		#urllib.urlretrieve()の関数の詳しい説明は参考リンクを見てください
		#参考リンク:http://peroon.hatenablog.com/entry/20090820/1250743144
		urllib.urlretrieve(downloadURL, savePath + count + ".png")
		return downloadURL
	except:
		newImageURL = url
		while urlFlag == 0:
			try:
				urllib.urlretrieve(newImageURL + downloadURL, savePath + count + ".png")
				while newImageURL[-1] != "/":
					newImageURL = newImageURL [:-1]

				urllib.urlretrieve(newImageURL + downloadURL, savePath + count + ".png")
				urlFlag = 1
				return newImageURL + downloadURL
			except:
				download_count += 1
				print "Failed... Fixing the problem"
			if download_count > 2:
				urlFlag = 1
				print "Error"

print "Donwloading images"

#ソースコードから「img src = 」と書いてある部分の検索
while (count < len(html)):
	if html[count] == "i" or html[count] == "I":
		count += 1
		if html[count] == "m" or html[count] == "M":
			count += 1
			if html[count] == "g" or html[count] == "G":
				count += 1
				if html[count] == " ":
					count += 1
				if html[count] == "s" or html[count] == "S":
					count += 1
					if html[count] == " ":
						count += 1
					if html[count] == "r" or html[count] == "R":
						count += 1
						if html[count] == " ":
							count += 1
						if html[count] == "c" or html[count] == "C":
							count += 1
							if html[count] == " ":
								count += 1
							if html[count] == "=":
								count += 1
								count = getImageURL(count)
								total_count += 1.0

	count += 1

#画像URLをテキストファイルで保存
fileName = savePath + "Download_URL.txt"
fileWrite = open(fileName, "w")

save_count = 0

fileWrite.write("Original HP = ")
fileWrite.write(url)
fileWrite.write("\n\n")

#同じ画像を重複しないように保存
already = 1
for i in imageURL:
	for j in alreadySaved:
		if i == j:
			already = 0
			break
		else:
			already = 1

	if already == 1:
		alreadySaved.append(i)
		savedURL = download(i, str(save_count))
		print savedURL
		try:
			fileWrite.write(savedURL)
		except:
			print "",
		fileWrite.write("\n")
	else:
		print "Already Saved"

	print format(rate, ".0f"),
	print "%"
	print "Success\n"
	rate = (save_count + 2) / total_count * 100
	save_count += 1

fileWrite.close()

#プログラムの終了
print "Download Completed"
try:
	print "Push Enter to finish"
	input()
	sys.exit()
except:
	sys.exit()


保存したいURLを変更したい場合はプログラムの

url = "http://www.geocities.jp/cba4jp/jyu00000/index.html"


の部分を変更してください.http://から入力しないと正常に動作しないので注意してください.

デフォルトでは某無料ウェブ漫画サイトになっています.

あとはPythonのプログラムを起動するだけで保存されます.


「なんじゃ,この見にくいプログラムは!!! コメントも雑だし!!!」

と思ってしまうかもしれませんが,申し訳ございません.

公開を前提として作っていなかったので,コメントも後付で非常に見にくいです.

次回からは公開を前提として考えます...

次回は(正確には次回があれば),今回公開したプログラムの詳しい説明をしていきたいです.


もし,質問がありましたらできる限りこたえていきます.

よろしくお願いします.