Downloading a picture via urllib and python

后端 未结 18 1590
离开以前
离开以前 2020-11-22 10:35

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 simila

18条回答
  •  一个人的身影
    2020-11-22 11:05

    What about this:

    import urllib, os
    
    def from_url( url, filename = None ):
        '''Store the url content to filename'''
        if not filename:
            filename = os.path.basename( os.path.realpath(url) )
    
        req = urllib.request.Request( url )
        try:
            response = urllib.request.urlopen( req )
        except urllib.error.URLError as e:
            if hasattr( e, 'reason' ):
                print( 'Fail in reaching the server -> ', e.reason )
                return False
            elif hasattr( e, 'code' ):
                print( 'The server couldn\'t fulfill the request -> ', e.code )
                return False
        else:
            with open( filename, 'wb' ) as fo:
                fo.write( response.read() )
                print( 'Url saved as %s' % filename )
            return True
    
    ##
    
    def main():
        test_url = 'http://cdn.sstatic.net/stackoverflow/img/favicon.ico'
    
        from_url( test_url )
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题