【发布时间】:2026-01-25 19:20:20
【问题描述】:
我正在使用 urllib2 打开一个 url。现在我需要将 html 文件作为字符串。我该怎么做?
【问题讨论】:
-
得到字符串后想做什么?最好的解决方案可能不涉及将文件读入字符串。
我正在使用 urllib2 打开一个 url。现在我需要将 html 文件作为字符串。我该怎么做?
【问题讨论】:
在python3中,应该改为urllib.request.openurl('http://www.example.com/').read().decode('utf-8')。
【讨论】:
最简单的方法是:
f = urllib2.urlopen("http://example.com/foo/bar")
s = f.read()
# s now holds the contents of the site
urllib2 docs有更多信息。
urlopen() 返回一个类似文件的对象,所以 Python 的 file object methods 工作。
【讨论】:
我认为在 python3 中 urllib.request.openurl('http://www.example.com/').read() 方法以二进制模式返回
【讨论】:
>>> import urllib2
>>> s = urllib2.urlopen('http://www.google.com').read()
>>> s
<big long string here>
【讨论】: