Python从URL读取页面?更好的文档?

2024-09-26 18:03:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用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.请求也是,但它是定义了URLLIB2。。。世贸基金会在这里举行?在

版本3.2.2


Tags: ofthein文档url网站errorurllib2
2条回答

按照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'

您可能引用的文档是the Python 2 documentation for ^{}。您可能应该使用的文档是the Python 3 documentation for ^{}。在

相关问题 更多 >

    热门问题