search

Home  >  Q&A  >  body text

python - 爬到图片的URL,如何下载到本地?

已经爬去到图片的URL,测试输出成功,如何才能把图片下载到本地?
方法一:

结果是

方法二:


结果是

新手求解,希望大神指出错误,给出改正方法,谢谢

PHPzPHPz2893 days ago317

reply all(7)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:25:36

    The open function opens a file. The question is, it is a directory.

    1

    2

    3

    4

    <code>>>> fp = open("git") #git是目录

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    IOError: [Errno 13] Permission denied: 'git'</code>

    Just add the file name.

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:25:36

    1

    2

    3

    4

    5

    6

    7

    8

    9

    <code class="python">import imghdr

     

    for i in imgurl:

        content = urllib2.urlopen(i).read()

        imgtype = imghdr.what('', h=content)

        if not imgtype:

            imgtype = 'txt'

        with open('F:\Download\{}.{}'.format(i, imgtype), 'wb') as f:

            f.write(content)</code>

    Obviously the file name was not included when writing

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:25:36

    There is no downloaded file name...

    1

    2

    3

    4

    5

    6

    7

    8

    <code>请输入代码

    def getImage(imList): 

        print 'Downloading...' 

        name = 1; 

        for imgurl in imList: 

            urllib.urlretrieve(imgurl, '%s.jpg' % name) 

            name += 1 

        print 'Got ', len(imList), ' images!' </code>

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:25:36

    Don’t use Chinese for the folder path, try changing it to an English path

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:25:36

    Please confirm whether writing a file directly using python can be successful. The error is caused by permissions.

    Replace the double quotes in the directory path with single quotes

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:25:36

    If there are Chinese characters in the path name, it is recommended to use Unicode format so that there will be no recognition errors

    reply
    0
  • 迷茫

    迷茫2017-04-18 09:25:36

    urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)

    This function. Simple and practical. It’s better to add exception handling

    reply
    0
  • Cancelreply