目的
对文本及符号密度的网页正文提取方法的源码进行解读
解读思路:
从基本的使用示例开始,通过分析其中的主类作为入口,了解项目的整体结构。
代码解读
from gne import GeneralNewsExtractor
extractor = GeneralNewsExtractor()
html = '你的目标网页正文'
result = extractor.extract(html)
print(result)
从基本的使用示例中看到,这里的处理的主类是 GeneralNewsExtractor 。处理的对象是 html 文本,处理得到的结果是字典对象。
下面来看看 GeneralNewsExtractor 中的代码内容,GeneralNewsExtractor 中共分为 3 个部分:
首先是 extract 函数的函数头的定义:
class GeneralNewsExtractor:
def extract(self,
html,
title_xpath='',
author_xpath='',
publish_time_xpath='',
host='',
body_xpath='',
noise_node_list=None,
with_body_html=False):
其次,函数中进行了对 html 内容的分解,
1、将 html 分解成对象节点
# 对 HTML 进行预处理可能会破坏 HTML 原有的结构,导致根据原始 HTML 编写的 XPath 不可用
# 因此,如果指定了 title_xpath/author_xpath/publish_time_xpath,那么需要先提取再进行
# 预处理
element = html2element(html)
2、从对象节点中提取标题
title = TitleExtractor().extract(element, title_xpath=title_xpath)
3、从对象节点中提取发布时间
publish_time = TimeExtractor().extractor(element, publish_time_xpath=publish_time_xpath)
4、从对象节点中提取作者
author = AuthorExtractor().extractor(element, author_xpath=author_xpath)
5、解析对象节点
element = pre_parse(element)
6、去除被认定为是噪声的节点
remove_noise_node(element, noise_node_list)
7、从对象中提取正文内容
content = Cont