I'm using urllib2 to open a url. Now I need th开发者_开发技巧e html file as a string. How do I do this?
In python3, it should be changed to urllib.request.openurl('http://www.example.com/').read().decode('utf-8')
.
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.
i think in python3 the urllib.request.openurl('http://www.example.com/').read() method return in binary mode
>>> import urllib2
>>> s = urllib2.urlopen('http://www.google.com').read()
>>> s
<big long string here>
精彩评论