代码来自于Python核心编程,运行环境为Python2.7+macOS。直至2月16日运行无误。代码中有核心代码注释,如需更详细的解释,请去书本内容观看。话不多说,直接上码。
#!/usr/bin/env python
import cStringIO
import formatter
from htmllib import HTMLParser
import httplib
import os
import sys
import urlparse
import urllib
#urllib:使用其中的urlparse()函数来下载Web页面。urlparse:使用其中的urlparse()和urljoin()函数来处理URL
class Retriever(object):
__slots__ = ('url','file')#__slot__变量表示实例只能拥有self.url和self.file属性
def __init__(self,url):
self.url,self.file=self.get_file(url)
def get_file(self,url,default='index.html'):
'Create usable local filename from url 将URL的前缀http://前缀移除,丢掉任何为获取主机名二附加的额外信息,如用户名、密码和端口号'
parsed=urlparse.urlparse(url)
host=parsed.netloc.split('@')[-1].split(':')[0]
filepath='%s%s' %(host,parsed.path)
if not os.path.splitext(parsed