そこで、ウェブコミックをダウンロードしてデスクトップのフォルダに配置する Python スクリプトを作成しようとしています。ここで、似たようなことをするいくつかの同様のプログラムを見つけましたが、必要なものとはまったく異なります。私が最も似ていると思ったものはここにあります( http://bytes.com/topic/python/answers/850927-problem-using-urllib-download-images )。私はこのコードを使用してみました:
>>> import urllib
>>> image = urllib.URLopener()
>>> image.retrieve("http://www.gunnerkrigg.com//comics/00000001.jpg","00000001.jpg")
('00000001.jpg', <httplib.HTTPMessage instance at 0x1457a80>)
次に、コンピューターで「00000001.jpg」というファイルを検索しましたが、キャッシュされた画像しか見つかりませんでした。ファイルが自分のコンピューターに保存されたかどうかさえわかりません。ファイルをダウンロードする方法を理解したら、残りの処理方法がわかったと思います。基本的には、for ループを使用して文字列を '00000000'.'jpg' で分割し、'00000000' を最大数までインクリメントします。これを行う最善の方法、またはファイルを正しくダウンロードする方法に関する推奨事項はありますか?
ありがとう!
編集 6/15/10
完成したスクリプトは次のとおりです。選択した任意のディレクトリにファイルが保存されます。何らかの奇妙な理由で、ファイルがダウンロードされていませんでした。それをきれいにする方法についての提案は大歓迎です。現在、特定の数の例外が発生した後にプログラムを終了させるのではなく、サイトに多数のコミックが存在することを確認して、最新のコミックだけを取得する方法を検討しています.
import urllib
import os
comicCounter=len(os.listdir('/file'))+1 # reads the number of files in the folder to start downloading at the next comic
errorCount=0
def download_comic(url,comicName):
"""
download a comic in the form of
url = http://www.example.com
comicName = '00000000.jpg'
"""
image=urllib.URLopener()
image.retrieve(url,comicName) # download comicName at URL
while comicCounter <= 1000: # not the most elegant solution
os.chdir('/file') # set where files download to
try:
if comicCounter < 10: # needed to break into 10^n segments because comic names are a set of zeros followed by a number
comicNumber=str('0000000'+str(comicCounter)) # string containing the eight digit comic number
comicName=str(comicNumber+".jpg") # string containing the file name
url=str("http://www.gunnerkrigg.com//comics/"+comicName) # creates the URL for the comic
comicCounter+=1 # increments the comic counter to go to the next comic, must be before the download in case the download raises an exception
download_comic(url,comicName) # uses the function defined above to download the comic
print url
if 10 <= comicCounter < 100:
comicNumber=str('000000'+str(comicCounter))
comicName=str(comicNumber+".jpg")
url=str("http://www.gunnerkrigg.com//comics/"+comicName)
comicCounter+=1
download_comic(url,comicName)
print url
if 100 <= comicCounter < 1000:
comicNumber=str('00000'+str(comicCounter))
comicName=str(comicNumber+".jpg")
url=str("http://www.gunnerkrigg.com//comics/"+comicName)
comicCounter+=1
download_comic(url,comicName)
print url
else: # quit the program if any number outside this range shows up
quit
except IOError: # urllib raises an IOError for a 404 error, when the comic doesn't exist
errorCount+=1 # add one to the error count
if errorCount>3: # if more than three errors occur during downloading, quit the program
break
else:
print str("comic"+ ' ' + str(comicCounter) + ' ' + "does not exist") # otherwise say that the certain comic number doesn't exist
print "all comics are up to date" # prints if all comics are downloaded