通过urllib和python下载图片

Mik*_*ike 169 python urllib urllib2

所以我正在尝试制作一个下载webcomics的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>)
Run Code Online (Sandbox Code Playgroud)

然后我在计算机上搜索了一个文件"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
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 227

使用urllib.urlretrieve:

import urllib
urllib.urlretrieve("http://www.gunnerkrigg.com//comics/00000001.jpg", "00000001.jpg")
Run Code Online (Sandbox Code Playgroud)

  • 请注意Python 3,您需要导入[url.request](https://docs.python.org/3.0/library/urllib.request.html#urllib.request.urlretrieve):`import urllib.request urllib.request .retrieve( "HTTP:// ......")` (56认同)
  • @wasabigeek在我看来是`urllib.request.urlretrieve("http:// ...")` (16认同)
  • 注意Python 3它实际上是`import urllib.request urllib.request.urlretrieve("http://...jpg","1.jpg")`.现在是3.x的'urlretrieve`. (15认同)

DiG*_*GMi 81

import urllib
f = open('00000001.jpg','wb')
f.write(urllib.urlopen('http://www.gunnerkrigg.com//comics/00000001.jpg').read())
f.close()
Run Code Online (Sandbox Code Playgroud)


ell*_*ial 57

仅供记录,使用请求库.

import requests
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
f.close()
Run Code Online (Sandbox Code Playgroud)

虽然它应该检查requests.get()错误.

  • 即使这个解决方案没有使用 urllib,您可能已经在 python 脚本中使用了 requests 库(这是我在搜索时的情况),所以您可能也想使用它来获取图片。 (2认同)

HIS*_*ISI 31

对于Python 3,您需要导入import urllib.request:

import urllib.request 

urllib.request.urlretrieve(url, filename)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看链接


Den*_*zov 14

@DiGMi的Python 3版本答案:

from urllib import request
f = open('00000001.jpg', 'wb')
f.write(request.urlopen("http://www.gunnerkrigg.com/comics/00000001.jpg").read())
f.close()
Run Code Online (Sandbox Code Playgroud)


Jan*_*ana 10

我找到了这个答案,我以更可靠的方式编辑

def download_photo(self, img_url, filename):
    try:
        image_on_web = urllib.urlopen(img_url)
        if image_on_web.headers.maintype == 'image':
            buf = image_on_web.read()
            path = os.getcwd() + DOWNLOADED_IMAGE_PATH
            file_path = "%s%s" % (path, filename)
            downloaded_image = file(file_path, "wb")
            downloaded_image.write(buf)
            downloaded_image.close()
            image_on_web.close()
        else:
            return False    
    except:
        return False
    return True
Run Code Online (Sandbox Code Playgroud)

从这里你永远不会在下载时获得任何其他资源或例外.

  • 你应该删除“自我” (2认同)

len*_*len 8

如果您知道文件位于dir网站的同一目录中site并具有以下格式:filename_01.jpg,...,filename_10.jpg然后下载所有文件:

import requests

for x in range(1, 10):
    str1 = 'filename_%2.2d.jpg' % (x)
    str2 = 'http://site/dir/filename_%2.2d.jpg' % (x)

    f = open(str1, 'wb')
    f.write(requests.get(str2).content)
    f.close()
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 7

最简单的方法是使用它.read()来读取部分或整个响应,然后将其写入您在已知良好位置打开的文件中.


小智 6

也许你需要'User-Agent':

import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36')]
response = opener.open('http://google.com')
htmlData = response.read()
f = open('file.txt','w')
f.write(htmlData )
f.close()
Run Code Online (Sandbox Code Playgroud)