I'm using urllib2 to open a url. Now I need the html file as a string. How do I do this?
+6
A:
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.
Nick Presta
2010-04-15 17:49:54
Thank you. That's perfect.
Nathan Lawrence
2010-04-21 16:05:12
A:
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> s = urllib2.urlopen('http://www.google.com').read()
>>> s
<big long string here>
jonesy
2010-04-16 00:06:26