urllib2到字符串

Nat*_*nce 6 python string urllib2

我正在使用urllib2打开一个网址.现在我需要将html文件作为字符串.我该怎么做呢?

Nic*_*sta 11

最简单的方法是:

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

urllib2文档中有更多信息.

urlopen()返回一个类文件对象,因此Python的文件对象方法有效.


Joe*_*ang 10

在python3中,它应该更改为urllib.request.openurl('http://www.example.com/').read().decode('utf-8').