【问题标题】:urllib2 to stringurllib2 到字符串
【发布时间】:2026-01-25 19:20:20
【问题描述】:

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

【问题讨论】:

  • 得到字符串后想做什么?最好的解决方案可能不涉及将文件读入字符串。

标签: python string urllib2


【解决方案1】:

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

【讨论】:

  • decode('utf-8') 是最简单的方法,很好的解决方案,否则你得到的是字节对象,只需执行 type() 你就会看到。
【解决方案2】:

最简单的方法是:

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 工作。

【讨论】:

    【解决方案3】:

    我认为在 python3 中 urllib.request.openurl('http://www.example.com/').read() 方法以二进制模式返回

    【讨论】:

      【解决方案4】:
      >>> import urllib2
      >>> s = urllib2.urlopen('http://www.google.com').read()
      >>> s
      <big long string here> 
      

      【讨论】: