Python从URL读取页面?更好的文档?
我在看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的文档上说:
urllib模块在Python 3.0中被拆分成几个部分,并重新命名为urllib.request、urllib.parse和urllib.error。2to3工具在将你的代码转换为3.0时会自动调整导入的内容。另外要注意,urllib.urlopen()函数在Python 3.0中被移除了,取而代之的是urllib2.urlopen()。
我也试着导入urllib.request,但它说urllib2是未定义的……到底发生了什么?
版本3.2.2
2 个回答
4
使用 urllib.request.open()
,这是在 《深入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'
3
你可能参考的文档是Python 2中关于urllib2
的文档。而你应该使用的文档是Python 3中关于urllib.request
的文档。