Search code examples
pythonstringurllib2

urllib2 to string


I'm using urllib2 to open a url. Now I need the html file as a string. How do I do this?


Solution

  • The easiest way would be:

    f = urllib2.urlopen("http://example.com/foo/bar")
    s = f.read()
    # s now holds the contents of the site
    

    There is more information in the urllib2 docs.

    urlopen() returns a file-like object, so Python's file object methods work.