CodyKochmann
1/30/2017 - 2:25 PM

get the size of a url in bytes in python

get the size of a url in bytes in python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# returns the number of bytes in a given url
# by: codykochmann

from urllib2 import urlopen

def url_size(link, timeout=3):
    """ returns the number of bytes that a given link weighs """
    try:
        return int(urlopen(link, timeout=timeout).info().getheaders("Content-Length")[0])
    except:
        # dont really care what happened here so just return 0
        return 0

if __name__ == '__main__':
    # this is just here if you wanna use it in the command line
    from sys import argv
    if len(argv) > 1:
        for i in argv[1:]:
            print(url_size(i))