python使用html2text库实现从HTML转markdown的方法详解


Posted in Python onFebruary 21, 2020

如果PyPi上搜html2text的话,找到的是另外一个库:Alir3z4/html2text。这个库是从aaronsw/html2text fork过来,并在此基础上对功能进行了扩展。因此是直接用pip安装的,因此本文主要来讲讲这个库。

首先,进行安装:

pip install html2text

命令行方式使用html2text

安装完后,就可以通过命令html2text进行一系列的操作了。

html2text命令使用方式为:html2text [(filename|url) [encoding]]。通过html2text -h,我们可以查看该命令支持的选项:

选项 描述
--version 显示程序版本号并退出
-h, --help 显示帮助信息并退出
--no-wrap-links 转换期间包装链接
--ignore-emphasis 对于强调,不包含任何格式
--reference-links 使用参考样式的链接,而不是内联链接
--ignore-links 对于链接,不包含任何格式
--protect-links 保护链接不换行,并用尖角括号将其围起来
--ignore-images 对于图像,不包含任何格式
--images-to-alt 丢弃图像数据,只保留替换文本
--images-with-size 将图像标签作为原生html,并带height和width属性,以保留维度
-g, --google-doc 转换一个被导出为html的谷歌文档
-d, --dash-unordered-list 对于无序列表,使用破折号而不是星号
-e, --asterisk-emphasis 对于被强调文本,使用星号而不是下划线
-b BODY_WIDTH, --body-width=BODY_WIDTH 每个输出行的字符数,0表示不自动换行
-i LIST_INDENT, --google-list-indent=LIST_INDENT Google缩进嵌套列表的像素数
-s, --hide-strikethrough 隐藏带删除线文本。只有当也指定-g的时候才有用
--escape-all 转义所有特殊字符。输出较为不可读,但是会避免极端情况下的格式化问题。
--bypass-tables 以HTML格式格式化表单,而不是Markdown语法。
--single-line-break 在一个块元素后使用单个换行符,而不是两个换行符。注意:要求?body-width=0
--unicode-snob 整个文档中都使用unicode
--no-automatic-links 在任何适用情况下,不要使用自动链接
--no-skip-internal-links 不要跳过内部链接
--links-after-para 将链接置于每段之后而不是文档之后
--mark-code 用 …将代码块标记出来
--decode-errors=DECODE_ERRORS 如何处理decode错误。接受值为'ignore', ‘strict'和'replace'

具体使用如下:

# 传递url
html2text http://eepurl.com/cK06Gn

# 传递文件名,编码方式设置为utf-8
html2text test.html utf-8

脚本中使用html2text

除了直接通过命令行使用html2text外,我们还可以在脚本中将其作为库导入。

我们以以下html文本为例

html_content = """
<span style="font-size:14px"><a href="http://blog.yhat.com/posts/visualize-nba-pipelines.html" rel="external nofollow" target="_blank" style="color: #1173C7;text-decoration: underline;font-weight: bold;">Data Wrangling 101: Using Python to Fetch, Manipulate & Visualize NBA Data</a></span><br>
A tutorial using pandas and a few other packages to build a simple datapipe for getting NBA data. Even though this tutorial is done using NBA data, you don't need to be an NBA fan to follow along. The same concepts and techniques can be applied to any project of your choosing.<br>
"""

一句话转换html文本为Markdown格式的文本:

import html2text
print html2text.html2text(html_content)

输出如下:

[Data Wrangling 101: Using Python to Fetch, Manipulate & Visualize NBA

Data](http://blog.yhat.com/posts/visualize-nba-pipelines.html)  

A tutorial using pandas and a few other packages to build a simple datapipe

for getting NBA data. Even though this tutorial is done using NBA data, you

don't need to be an NBA fan to follow along. The same concepts and techniques

can be applied to any project of your choosing.

另外,还可以使用上面的配置项:

import html2text
h = html2text.HTML2Text()
print h.handle(html_content) # 输出同上

注意:下面仅展示使用某个配置项时的输出,不使用某个配置项时使用默认值的输出(如无特殊说明)同上。

--ignore-emphasis

指定选项?ignore-emphasis

h.ignore_emphasis = True
print h.handle("<p>hello, this is <em>Ele</em></p>")

输出为:

hello, this is Ele

不指定选项?ignore-emphasis

h.ignore_emphasis = False # 默认值
print h.handle("<p>hello, this is <em>Ele</em></p>")

输出为:

hello, this is _Ele_

--reference-links

h.inline_links = False
print h.handle(html_content)

输出为:

[Data Wrangling 101: Using Python to Fetch, Manipulate & Visualize NBA

Data][16]  

A tutorial using pandas and a few other packages to build a simple datapipe

for getting NBA data. Even though this tutorial is done using NBA data, you

don't need to be an NBA fan to follow along. The same concepts and techniques

can be applied to any project of your choosing.  

   [16]: http://blog.yhat.com/posts/visualize-nba-pipelines.html

--ignore-links

h.ignore_links = True
print h.handle(html_content)

输出为:

Data Wrangling 101: Using Python to Fetch, Manipulate & Visualize NBA Data  

A tutorial using pandas and a few other packages to build a simple datapipe

for getting NBA data. Even though this tutorial is done using NBA data, you

don't need to be an NBA fan to follow along. The same concepts and techniques

can be applied to any project of your choosing.

--protect-links

h.protect_links = True
print h.handle(html_content)

输出为:

[Data Wrangling 101: Using Python to Fetch, Manipulate & Visualize NBA

Data](<http://blog.yhat.com/posts/visualize-nba-pipelines.html>)  

A tutorial using pandas and a few other packages to build a simple datapipe

for getting NBA data. Even though this tutorial is done using NBA data, you

don't need to be an NBA fan to follow along. The same concepts and techniques

can be applied to any project of your choosing.

--ignore-images

h.ignore_images = True
print h.handle('<p>This is a img: <img src="https://my.oschina.net/img/hot3.png" style="max-height: 32px; max-width: 32px;" alt="hot3"> ending ...</p>')

输出为:

This is a img:  ending ...

--images-to-alt

h.images_to_alt = True
print h.handle('<p>This is a img: <img src="https://my.oschina.net/img/hot3.png" style="max-height: 32px; max-width: 32px;" alt="hot3"> ending ...</p>')

输出为:

This is a img: hot3 ending ...

--images-with-size

h.images_with_size = True
print h.handle('<p>This is a img: <img src="https://my.oschina.net/img/hot3.png" height=32px width=32px alt="hot3"> ending ...</p>')

输出为:

This is a img: <img src='https://my.oschina.net/img/hot3.png' width='32px'

height='32px' alt='hot3' /> ending ...

--body-width

h.body_width=0
print h.handle(html_content)

输出为:

[Data Wrangling 101: Using Python to Fetch, Manipulate & Visualize NBA Data](http://blog.yhat.com/posts/visualize-nba-pipelines.html)  

A tutorial using pandas and a few other packages to build a simple datapipe for getting NBA data. Even though this tutorial is done using NBA data, you don't need to be an NBA fan to follow along. The same concepts and techniques can be applied to any project of your choosing.

--mark-code

h.mark_code=True
print h.handle('<pre class="hljs css"><code class="hljs css">    <span class="hljs-selector-tag"><span class="hljs-selector-tag">rpm</span></span> <span class="hljs-selector-tag"><span class="hljs-selector-tag">-Uvh</span></span> <span class="hljs-selector-tag"><span class="hljs-selector-tag">erlang-solutions-1</span></span><span class="hljs-selector-class"><span class="hljs-selector-class">.0-1</span></span><span class="hljs-selector-class"><span class="hljs-selector-class">.noarch</span></span><span class="hljs-selector-class"><span class="hljs-selector-class">.rpm</span></span></code></pre>')

输出为:

        rpm -Uvh erlang-solutions-1.0-1.noarch.rpm

通过这种方式,就可以以脚本的形式自定义HTML -> MARKDOWN的自动化过程了。例子可参考下面的例子

#-*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8') 
import re
import requests
from lxml import etree
import html2text


# 获取第一个issue
def get_first_issue(url):
  resp = requests.get(url)
  page = etree.HTML(resp.text)
  issue_list = page.xpath("//ul[@id='archive-list']/div[@class='display_archive']/li/a")
  fst_issue = issue_list[0].attrib
  fst_issue["text"] = issue_list[0].text
  return fst_issue


# 获取issue的内容,并转成markdown
def get_issue_md(url):
  resp = requests.get(url)
  page = etree.HTML(resp.text)
  content = page.xpath("//table[@id='templateBody']")[0]#'//table[@class="bodyTable"]')[0]
  h = html2text.HTML2Text()
  h.body_width=0 # 不自动换行
  return h.handle(etree.tostring(content))

subtitle_mapping = {
  '**From Our Sponsor**': '# 来自赞助商',
  '**News**': '# 新闻',
  '**Articles**,** Tutorials and Talks**': '# 文章,教程和讲座',
  '**Books**': '# 书籍',
  '**Interesting Projects, Tools and Libraries**': '# 好玩的项目,工具和库',
  '**Python Jobs of the Week**': '# 本周的Python工作',
  '**New Releases**': '# 最新发布',
  '**Upcoming Events and Webinars**': '# 近期活动和网络研讨会',
}
def clean_issue(content):
  # 去除‘Share Python Weekly'及后面部分
  content = re.sub('\*\*Share Python Weekly.*', '', content, flags=re.IGNORECASE)
  # 预处理标题
  for k, v in subtitle_mapping.items():
    content = content.replace(k, v)
  return content

tpl_str = """原文:[{title}]({url})
---
{content}
"""
def run():
  issue_list_url = "https://us2.campaign-archive.com/home/?u=e2e180baf855ac797ef407fc7&id=9e26887fc5"
  print "开始获取最新的issue……"
  fst = get_first_issue(issue_list_url)
  #fst = {'href': 'http://eepurl.com/dqpDyL', 'title': 'Python Weekly - Issue 341'}
  print "获取完毕。开始截取最新的issue内容并将其转换成markdown格式"
  content = get_issue_md(fst['href'])
  print "开始清理issue内容"
  content = clean_issue(content)

  print "清理完毕,准备将", fst['title'], "写入文件"
  title = fst['title'].replace('- ', '').replace(' ', '_')
  with open(title.strip()+'.md', "wb") as f:
    f.write(tpl_str.format(title=fst['title'], url=fst['href'], content=content))
  print "恭喜,完成啦。文件保存至%s.md" % title

if __name__ == '__main__':
  run()

这是一个每周跑一次的python weekly转markdown的脚本。

好啦,html2text就介绍到这里了。如果觉得它还不能满足你的要求,或者想添加更多的功能,可以fork并自行修改。

Python 相关文章推荐
Python3.x和Python2.x的区别介绍
Feb 12 Python
python Django批量导入不重复数据
Mar 25 Python
关于Python中Inf与Nan的判断问题详解
Feb 08 Python
python单线程文件传输的实例(C/S)
Feb 13 Python
Django如何开发简单的查询接口详解
May 17 Python
Python 等分切分数据及规则命名的实例代码
Aug 16 Python
django ajax发送post请求的两种方法
Jan 05 Python
利用python生成照片墙的示例代码
Apr 09 Python
Softmax函数原理及Python实现过程解析
May 22 Python
详解Python IO口多路复用
Jun 17 Python
如何在Python项目中引入日志
May 31 Python
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
Jun 09 Python
python-sys.stdout作为默认函数参数的实现
Feb 21 #Python
pycharm运行程序时看不到任何结果显示的解决
Feb 21 #Python
Python 安装 virturalenv 虚拟环境的教程详解
Feb 21 #Python
python ffmpeg任意提取视频帧的方法
Feb 21 #Python
Python实现自动访问网页的例子
Feb 21 #Python
解决Python pip 自动更新升级失败的问题
Feb 21 #Python
python利用百度云接口实现车牌识别的示例
Feb 21 #Python
You might like
PHP新手上路(七)
2006/10/09 PHP
PHP HTML JavaScript MySQL代码如何互相传值的方法分享
2012/09/30 PHP
探讨php中防止SQL注入最好的方法是什么
2013/06/10 PHP
从刷票了解获得客户端IP的方法
2015/09/21 PHP
php 计算两个时间相差的天数、小时数、分钟数、秒数详解及实例代码
2016/11/09 PHP
javascript判断单选框或复选框是否选中方法集锦
2007/04/04 Javascript
jquery ajax 检测用户注册时用户名是否存在
2009/11/03 Javascript
Ext grid 添加右击菜单
2009/11/26 Javascript
深入了解javascript中的prototype与继承
2013/04/14 Javascript
PHP PDO操作总结
2014/11/17 Javascript
JS实现仿雅虎首页快捷登录入口及导航模块效果
2015/09/19 Javascript
ECharts仪表盘实例代码(附源码下载)
2016/02/18 Javascript
IE和Firefox之间在JavaScript语法上的差异
2016/04/22 Javascript
Angular 路由route实例代码
2016/07/12 Javascript
React如何将组件渲染到指定DOM节点详解
2017/09/08 Javascript
微信小程序实现多个按钮的颜色状态转换
2019/02/15 Javascript
微信小程序实现点击空白隐藏的方法示例
2019/08/13 Javascript
[46:43]DOTA2上海特级锦标赛D组小组赛#1 EG VS COL第三局
2016/02/28 DOTA
在Python中使用HTMLParser解析HTML的教程
2015/04/29 Python
python创建和删除目录的方法
2015/04/29 Python
Python连接DB2数据库
2016/08/27 Python
Python 定义只读属性的实现方式
2020/03/05 Python
python实现在内存中读写str和二进制数据代码
2020/04/24 Python
序列化Python对象的方法
2020/08/01 Python
CSS3 translate导致字体模糊的实例代码
2019/08/30 HTML / CSS
css3实例教程 一款纯css3实现的发光屏幕旋转特效
2014/12/07 HTML / CSS
Html5 webRTC简单实现视频调用的示例代码
2020/09/23 HTML / CSS
女子锻炼服装和瑜伽服装:Splits59
2019/03/04 全球购物
一篇.NET面试题
2014/09/29 面试题
2014党委书记四风对照检查材料思想汇报
2014/09/21 职场文书
常务副县长“三严三实”对照检查材料思想汇报
2014/10/05 职场文书
2014年终工作总结范本
2014/12/15 职场文书
辞职信标准格式
2015/02/27 职场文书
安装pytorch时报sslerror错误的解决方案
2021/05/17 Python
Java界面编程实现界面跳转
2022/06/16 Java/Android
SQLyog的下载、安装、破解、配置教程(MySQL可视化工具安装)
2022/09/23 MySQL