Skip to main content
 首页 » 编程设计

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

2025年05月04日15JustinYoung

我在使用 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。将源代码转换为 3.0 时,2to3 工具会自动调整导入。另请注意,urllib.urlopen() 函数已在 Python 3.0 中删除,取而代之的是 urllib2.urlopen()。

我也尝试过导入 urllib.request,但它说 urllib 2 已定义...WTF 在这里进行?

版本 3.2.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'