开发者

urllib2 to string

开发者 https://www.devze.com 2022-12-27 14:24 出处:网络
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().d

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> 
0

精彩评论

暂无评论...
验证码 换一张
取 消