Urllib2 to string

I am using urllib2 to open a url. Now I need an html file as a string. How to do it?

+6
python string urllib2
source share
4 answers

The easiest way:

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

The urllib2 docs have more info.

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

+10
source share

In python3, it should be changed to urllib.request.openurl('http://www.example.com/').read().decode('utf-8') .

+7
source share

I think in python3 urllib.request.openurl (' http://www.example.com/ '). The return () method returns in binary mode

+4
source share
 >>> import urllib2 >>> s = urllib2.urlopen('http://www.google.com').read() >>> s <big long string here> 
+1
source share

All Articles