python 提取html文本的方法


Posted in Python onMay 20, 2021

假设我们需要从各种网页中提取全文,并且要剥离所有HTML标记。通常,默认解决方案是使用BeautifulSoup软件包中的get_text方法,该方法内部使用lxml。这是一个经过充分测试的解决方案,但是在处理成千上万个HTML文档时可能会非常慢。
通过用selectolax替换BeautifulSoup,您几乎可以免费获得5-30倍的加速!
这是一个简单的基准测试,可分析commoncrawl(`处理NLP问题时,有时您需要获得大量的文本集。互联网是文本的最大来源,但是不幸的是,从任意HTML页面提取文本是一项艰巨而痛苦的任务。
假设我们需要从各种网页中提取全文,并且要剥离所有HTML标记。通常,默认解决方案是使用BeautifulSoup软件包中的get_text方法,该方法内部使用lxml。这是一个经过充分测试的解决方案,但是在处理成千上万个HTML文档时可能会非常慢。
通过用selectolax替换BeautifulSoup,您几乎可以免费获得5-30倍的加速!这是一个简单的基准测试,可分析commoncrawl(https://commoncrawl.org/)的10,000个HTML页面:

# coding: utf-8

from time import time

import warc
from bs4 import BeautifulSoup
from selectolax.parser import HTMLParser


def get_text_bs(html):
    tree = BeautifulSoup(html, 'lxml')

    body = tree.body
    if body is None:
        return None

    for tag in body.select('script'):
        tag.decompose()
    for tag in body.select('style'):
        tag.decompose()

    text = body.get_text(separator='\n')
    return text


def get_text_selectolax(html):
    tree = HTMLParser(html)

    if tree.body is None:
        return None

    for tag in tree.css('script'):
        tag.decompose()
    for tag in tree.css('style'):
        tag.decompose()

    text = tree.body.text(separator='\n')
    return text


def read_doc(record, parser=get_text_selectolax):
    url = record.url
    text = None

    if url:
        payload = record.payload.read()
        header, html = payload.split(b'\r\n\r\n', maxsplit=1)
        html = html.strip()

        if len(html) > 0:
            text = parser(html)

    return url, text


def process_warc(file_name, parser, limit=10000):
    warc_file = warc.open(file_name, 'rb')
    t0 = time()
    n_documents = 0
    for i, record in enumerate(warc_file):
        url, doc = read_doc(record, parser)

        if not doc or not url:
            continue

        n_documents += 1

        if i > limit:
            break

    warc_file.close()
    print('Parser: %s' % parser.__name__)
    print('Parsing took %s seconds and produced %s documents\n' % (time() - t0, n_documents))
>>> ! wget https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2018-05/segments/1516084886237.6/warc/CC-MAIN-20180116070444-20180116090444-00000.warc.gz
>>> file_name = "CC-MAIN-20180116070444-20180116090444-00000.warc.gz"
>>> process_warc(file_name, get_text_selectolax, 10000)
Parser: get_text_selectolax
Parsing took 16.170367002487183 seconds and produced 3317 documents
>>> process_warc(file_name, get_text_bs, 10000)
Parser: get_text_bs
Parsing took 432.6902508735657 seconds and produced 3283 documents

显然,这并不是对某些事物进行基准测试的最佳方法,但是它提供了一个想法,即selectolax有时比lxml快30倍。
selectolax最适合将HTML剥离为纯文本。如果我有10,000多个HTML片段,需要将它们作为纯文本索引到Elasticsearch中。(Elasticsearch有一个html_strip文本过滤器,但这不是我想要/不需要在此上下文中使用的过滤器)。事实证明,以这种规模将HTML剥离为纯文本实际上是非常低效的。那么,最有效的方法是什么?

  • PyQuery
from pyquery import PyQuery as pq

text = pq(html).text()
  • selectolax
from selectolax.parser import HTMLParser

text = HTMLParser(html).text()
  • 正则表达式
import re

regex = re.compile(r'<.*?>')
text = clean_regex.sub('', html)

结果

我编写了一个脚本来计算时间,该脚本遍历包含HTML片段的10,000个文件。注意!这些片段不是完整的<html>文档(带有<head>和<body>等),只是HTML的一小部分。平均大小为10,314字节(中位数为5138字节)。结果如下:

pyquery
  SUM:    18.61 seconds
  MEAN:   1.8633 ms
  MEDIAN: 1.0554 ms
selectolax
  SUM:    3.08 seconds
  MEAN:   0.3149 ms
  MEDIAN: 0.1621 ms
regex
  SUM:    1.64 seconds
  MEAN:   0.1613 ms
  MEDIAN: 0.0881 ms

我已经运行了很多次,结果非常稳定。重点是:selectolax比PyQuery快7倍。

正则表达式好用?真的吗?

对于最基本的HTML Blob,它可能工作得很好。实际上,如果HTML是<p> Foo&amp; Bar </ p>,我希望纯文本转换应该是Foo&Bar,而不是Foo&amp; bar。
更重要的一点是,PyQuery和selectolax支持非常特定但对我的用例很重要的内容。在继续之前,我需要删除某些标签(及其内容)。例如:

<h4 class="warning">This should get stripped.</h4>
<p>Please keep.</p>
<div style="display: none">This should also get stripped.</div>

正则表达式永远无法做到这一点。

2.0 版本

因此,我的要求可能会发生变化,但基本上,我想删除某些标签。例如:<div class =“ warning”>  、 <div class =“ hidden”> 和 <div style =“ display:none”>。因此,让我们实现一下:

  • PyQuery
from pyquery import PyQuery as pq

_display_none_regex = re.compile(r'display:\s*none')

doc = pq(html)
doc.remove('div.warning, div.hidden')
for div in doc('div[style]').items():
    style_value = div.attr('style')
    if _display_none_regex.search(style_value):
        div.remove()
text = doc.text()
  • selectolax
from selectolax.parser import HTMLParser

_display_none_regex = re.compile(r'display:\s*none')

tree = HTMLParser(html)
for tag in tree.css('div.warning, div.hidden'):
    tag.decompose()
for tag in tree.css('div[style]'):
    style_value = tag.attributes['style']
    if style_value and _display_none_regex.search(style_value):
        tag.decompose()
text = tree.body.text()

这实际上有效。当我现在为10,000个片段运行相同的基准时,新结果如下:

pyquery
  SUM:    21.70 seconds
  MEAN:   2.1701 ms
  MEDIAN: 1.3989 ms
selectolax
  SUM:    3.59 seconds
  MEAN:   0.3589 ms
  MEDIAN: 0.2184 ms
regex
  Skip

同样,selectolax击败PyQuery约6倍。

结论

正则表达式速度快,但功能弱。selectolax的效率令人印象深刻。

以上就是python 提取html文本的方法的详细内容,更多关于python 提取html文本的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python学习笔记_数据排序方法
May 22 Python
Python中装饰器的一个妙用
Feb 08 Python
在Python编程过程中用单元测试法调试代码的介绍
Apr 02 Python
Python使用pygame模块编写俄罗斯方块游戏的代码实例
Dec 08 Python
python回调函数中使用多线程的方法
Dec 25 Python
浅述python2与python3的简单区别
Sep 19 Python
Django框架中间件(Middleware)用法实例分析
May 24 Python
把django中admin后台界面的英文修改为中文显示的方法
Jul 26 Python
Python中six模块基础用法
Dec 08 Python
Python 字节流,字符串,十六进制相互转换实例(binascii,bytes)
May 11 Python
Pandas对DataFrame单列/多列进行运算(map, apply, transform, agg)
Jun 14 Python
Python实现对word文档添加密码去除密码的示例代码
Dec 29 Python
学会用Python实现滑雪小游戏,再也不用去北海道啦
pytorch 带batch的tensor类型图像显示操作
pytorch 中nn.Dropout的使用说明
May 20 #Python
Python 线程池模块之多线程操作代码
May 20 #Python
pytorch中[..., 0]的用法说明
May 20 #Python
浅谈pytorch中stack和cat的及to_tensor的坑
May 20 #Python
pytorch实现手写数字图片识别
You might like
深入PHP curl参数的详解
2013/06/17 PHP
php获取随机数组列表的方法
2014/11/13 PHP
PHP receiveMail实现收邮件功能
2018/04/25 PHP
用JavaScript编写COM组件的步骤
2009/03/17 Javascript
jQuery学习笔记之jQuery的DOM操作
2010/12/22 Javascript
jQuery 源码分析笔记(6) jQuery.data
2011/06/08 Javascript
jQuery实现响应鼠标滚动的动感菜单效果
2015/09/21 Javascript
详解WordPress开发中get_current_screen()函数的使用
2016/01/11 Javascript
jQuery与Ajax以及序列化
2016/02/01 Javascript
jQuery+ajax+asp.net获取Json值的方法
2016/06/08 Javascript
微信小程序 es6-promise.js封装请求与处理异步进程
2017/06/12 Javascript
js排序与重组的实例讲解
2017/08/28 Javascript
基于JavaScript实现前端数据多条件筛选功能
2020/08/19 Javascript
Vue2.0+ElementUI实现表格翻页的实例
2017/10/23 Javascript
jQuery.extend 与 jQuery.fn.extend的用法及区别实例分析
2018/07/25 jQuery
对vue v-if v-else-if v-else 的简单使用详解
2018/09/29 Javascript
详解vue-cli3多页应用改造
2019/06/04 Javascript
[02:32]DOTA2英雄基础教程 美杜莎
2014/01/07 DOTA
Python中实现两个字典(dict)合并的方法
2014/09/23 Python
Windows下为Python安装Matplotlib模块
2015/11/06 Python
Python实现的插入排序算法原理与用法实例分析
2017/11/22 Python
python OpenCV学习笔记实现二维直方图
2018/02/08 Python
python寻找list中最大值、最小值并返回其所在位置的方法
2018/06/27 Python
pyside+pyqt实现鼠标右键菜单功能
2020/12/08 Python
Python实现时间序列可视化的方法
2019/08/06 Python
python从内存地址上加载python对象过程详解
2020/01/08 Python
在django admin详情表单显示中添加自定义控件的实现
2020/03/11 Python
python 实现仿微信聊天时间格式化显示的代码
2020/04/17 Python
Django使用Profile扩展User模块方式
2020/05/14 Python
美国最大的无人机经销商:DroneNerds
2018/03/20 全球购物
小学五年级学生评语
2014/04/22 职场文书
教代会开幕词
2015/01/28 职场文书
2016年感恩节活动总结大全
2016/04/01 职场文书
SQL 聚合、分组和排序
2021/11/11 MySQL
springboot layui hutool Excel导入的实现
2022/03/31 Java/Android
什么是css原子化,有什么用?
2022/04/24 HTML / CSS