티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Downloading a picture via urllib and python

urllib 및 python을 통해 사진 다운로드

 문제 내용 

So I'm trying to make a Python script that downloads webcomics and puts them in a folder on my desktop. I've found a few similar programs on here that do something similar, but nothing quite like what I need. The one that I found most similar is right here (http://bytes.com/topic/python/answers/850927-problem-using-urllib-download-images). I tried using this code:

그래서 나는 웹코믹스를 다운받아 내 바탕화면의 폴더에 넣는 파이썬 스크립트를 만들려고 한다. 나는 여기서 비슷한 프로그램을 몇 개 찾았지만, 내가 필요로 하는 것과 비슷한 것은 없었다. 내가 가장 비슷한 것을 발견한 것은 바로 여기 (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>)

I then searched my computer for a file "00000001.jpg", but all I found was the cached picture of it. I'm not even sure it saved the file to my computer. Once I understand how to get the file downloaded, I think I know how to handle the rest. Essentially just use a for loop and split the string at the '00000000'.'jpg' and increment the '00000000' up to the largest number, which I would have to somehow determine. Any reccomendations on the best way to do this or how to download the file correctly?

그리고 나서 나는 내 컴퓨터에서 "00000001.jpg" 파일을 검색했지만, 내가 찾은 것은 그것의 캐시된 사진뿐이었다. 내 컴퓨터에 파일이 저장되었는지도 모르겠어요. 파일을 다운로드 받는 방법을 이해하고 나면 나머지를 처리하는 방법을 알 수 있을 것 같습니다. 기본적으로 for 루프를 사용하고 '000000'.jpg'에서 문자열을 분할하고 '00000000'을 가장 큰 숫자까지 증가시키면 됩니다. 어떻게든 결정해야 할 것입니다. 이 작업을 수행하는 가장 좋은 방법이나 파일을 올바르게 다운로드하는 방법에 대한 권장 사항이 있습니까?

 

Thanks!

감사합니다!

 

EDIT 6/15/10

편집 6/15/10

 

Here is the completed script, it saves the files to any directory you choose. For some odd reason, the files weren't downloading and they just did. Any suggestions on how to clean it up would be much appreciated. I'm currently working out how to find out many comics exist on the site so I can get just the latest one, rather than having the program quit after a certain number of exceptions are raised.

다음은 완성된 스크립트이며 선택한 디렉토리에 파일을 저장합니다. 이상한 이유로 파일이 다운로드되지 않고 그냥 다운로드되었습니다. 그것을 정리하는 방법에 대한 제안은 대단히 감사하겠습니다. 저는 현재 특정 수의 예외가 발생한 후 프로그램을 종료하는 대신 최신 만화를 얻을 수 있도록 사이트에 많은 만화가 존재하는지 알아내는 방법을 연구하고 있습니다.
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

 

 

 높은 점수를 받은 Solution 

Python 2

파이썬 2

Using urllib.urlretrieve

urllib.urlreetrieve 사용
import urllib
urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")

 

Python 3

파이썬 3

Using urllib.request.urlretrieve (part of Python 3's legacy interface, works exactly the same)

urllib.request.urlretrieve 사용(파이썬 3의 레거시 인터페이스의 일부로 정확히 동일하게 작동)
import urllib.request
urllib.request.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")

 

 

 가장 최근 달린 Solution 

Using urllib, you can get this done instantly.

Urllib을 사용하면 즉시 이 작업을 수행할 수 있습니다.
import urllib.request

opener=urllib.request.build_opener()
opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36')]
urllib.request.install_opener(opener)

urllib.request.urlretrieve(URL, "images/0.jpg")

 

 

출처 : https://stackoverflow.com/questions/3042757/downloading-a-picture-via-urllib-and-python

반응형
댓글
공지사항
최근에 올라온 글