【发布时间】:2018-05-22 02:20:44
【问题描述】:
我正在尝试使用 Aaron Swartz 的 Python html2text 库(在 Python 2.7 上)。我没有成功在包含 URL 具有特殊字符的链接的字符串上使用 html2text()。例如:
# -*- coding: utf-8 -*-
import html2text
s = u'Link <a href="https://en.wikipedia.org/wiki/Málaga">here</a>!'
str = html2text.html2text(s)
因错误而失败:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 31: ordinal not in range(128)
鉴于:
# -*- coding: utf-8 -*-
import html2text
s = u'<a href="https://en.wikipedia.org/wiki/Malaga">héré</a>!'
str = html2text.html2text(s)
(有特殊字符,但只在文本中,不在 URL 中)工作得很好。
我一定是在编码方面遗漏了一些东西,但我在文档中找不到任何东西。有没有办法告诉 html2text 在其 url 解析器中使用非 ascii 编码器?
【问题讨论】:
-
那些类似 URL 的字符串是从哪里来的?非 ascii 字符在 URL 中无效,因此问题是您是否有需要容忍的错误输入,或者您是否不小心在某处取消了有效 URI,例如该页面上的
<link rel="canonical" href="https://en.wikipedia.org/wiki/M%C3%A1laga"/>版本。跨度> -
@PeterDeGlopper 需要容忍的错误输入!自动转换为规范版本将是理想的。
标签: python python-2.7 url encoding