【问题标题】:Python read page from URL? Better documentation?Python从URL读取页面?更好的文档?
【发布时间】:2011-11-28 21:07:59
【问题描述】:

我在使用 Python 的文档时遇到了很多麻烦。有没有类似 Mozilla 开发者网络的东西?

我正在做一个 Python 拼图网站,我需要能够阅读页面的内容。我在一个网站上看到了以下内容:

import urllib2

urlStr = 'http://www.python.org/'
try:
  fileHandle = urllib2.urlopen(urlStr)
  str1 = fileHandle.read()
  fileHandle.close()
  print ('-'*50)
  print ('HTML code of URL =', urlStr)
  print ('-'*50)
except IOError:
  print ('Cannot open URL %s for reading' % urlStr)
  str1 = 'error!'

print (str1)

它一直说没有 urllib2 模块。

Python 文档说

The urllib module has been split into parts and renamed in Python 3.0 to urllib.request, urllib.parse, and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to 3.0. Also note that the urllib.urlopen() function has been removed in Python 3.0 in favor of urllib2.urlopen().

我也尝试导入 urllib.request,但它说 urllib 2 已定义... WTF 在这里发生吗?

版本 3.2.2

【问题讨论】:

  • 此时您的 Python 版本会很有用。
  • 已更新。除了给定的内容之外,还有其他 Python 文档吗?
  • 这是您使用的文档吗? docs.python.org/py3k
  • 是的,是的。我一直在用那个。 @icktoofay 谢谢,这有帮助。那我必须做 urllib.request.openurl 。谢谢,把它作为答案,我会接受它。

标签: python url urllib


【解决方案1】:

您可能引用的文档是the Python 2 documentation for urllib2。您可能应该使用的文档是the Python 3 documentation for urllib.request

【讨论】:

    【解决方案2】:

    使用urllib.request.open(),如Dive into Python 3 中的建议...

    Python 3.2.1 (default, Jul 24 2011, 22:21:06) 
    [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import urllib.request
    >>> urlStr = 'http://www.python.org/'
    >>> fileHandle = urllib.request.urlopen(urlStr)
    >>> print(fileHandle.read()[:100])
    b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtm'
    

    【讨论】:

    • 现在文件 fileHandle 包含完整的源代码。如何使用 fileHandle 数据上的 xpath 来获取特定值?
    • @DixitSingla:你可以使用lxml,就像这个答案:stackoverflow.com/a/11466033/78845
    猜你喜欢
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多