-  
项目背景
在python 即时网络爬虫项目启动说明中我们讨论一个数字:程序员浪费在调测内容提取规则上的时间,从而我们发起了这个项目,把程序员从繁琐的调测规则中解放出来,投入到更高端的数据处理工作中。 -  
解决方案
为了解决这个问题,我们把影响通用性和工作效率的提取器隔离出来,描述了如下的数据处理流程图:

图中“可插拔提取器”必须很强的模块化,那么关键的接口有:
标准化的输入:以标准的HTML DOM对象为输入
标准化的内容提取:使用标准的xslt模板提取网页内容
标准化的输出:以标准的XML格式输出从网页上提取到的内容
明确的提取器插拔接口:提取器是一个明确定义的类,通过类方法与爬虫引擎模块交互 -  
提取器代码
可插拔提取器是即时网络爬虫项目的核心组件,定义成一个类: GsExtractor
使用模式是这样的:
实例化一个GsExtractor对象
为这个对象设定xslt提取器,相当于把这个对象配置好(使用三类setXXX()方法)
把html dom输入给它,就能获得xml输出(使用extract()方法)
下面是这个GsExtractor类的源代码(适用于Python3)
#!/usr/bin/python 
-- coding: utf-8 --
模块名: gooseeker
类名: GsExtractor
Version: 2.0
适配Python版本: Python3
说明: html内容提取器
功能: 使用xslt作为模板,快速提取HTML DOM中的内容。
released by 集搜客(http://www.gooseeker.com) on May 18, 2016
github: https://github.com/FullerHua/jisou/core/gooseeker.py
from urllib import request
 from urllib.parse import quote
 from lxml import etree
 import time
class GsExtractor(object):
 def init(self):
 self.xslt = “”
 # 从文件读取xslt
 def setXsltFromFile(self , xsltFilePath):
 file = open(xsltFilePath , ‘r’ , encoding=‘UTF-8’)
 try:
 self.xslt = file.read()
 finally:
 file.close()
 # 从字符串获得xslt
 def setXsltFromMem(self , xsltStr):
 self.xslt = xsltStr
 # 通过GooSeeker API接口获得xslt
 def setXsltFromAPI(self , APIKey , theme, middle=None, bname=None):
 apiurl = “http://www.gooseeker.com/api/getextractor?key=”+ APIKey +“&theme=”+quote(theme)
 if (middle):
 apiurl = apiurl + “&middle=”+quote(middle)
 if (bname):
 apiurl = apiurl + “&bname=”+quote(bname)
 apiconn = request.urlopen(apiurl)
 self.xslt = apiconn.read()
 # 返回当前xslt
 def getXslt(self):
 return self.xslt
 # 提取方法,入参是一个HTML DOM对象,返回是提取结果
 def extract(self , html):
 xslt_root = etree.XML(self.xslt)
 transform = etree.XSLT(xslt_root)
 result_tree = transform(html)
 return result_tree


















