【问题标题】:html2text: How to parse urls containing special characters?html2text:如何解析包含特殊字符的网址?
【发布时间】: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,例如该页面上的 &lt;link rel="canonical" href="https://en.wikipedia.org/wiki/M%C3%A1laga"/&gt; 版本。跨度>
  • @PeterDeGlopper 需要容忍的错误输入!自动转换为规范版本将是理想的。

标签: python python-2.7 url encoding


【解决方案1】:

您可以使用urllib.quote(Python3 中的urllib.parse.quote)对非ascii 字符进行编码。 safe 参数中指定的字符将不会被编码。

import html2text
from urllib import quote

s = 'Link <a href="https://en.wikipedia.org/wiki/Málaga">here</a>!'
q = quote(s, safe=' <>="/:!')
s = html2text.html2text(q)

print q
print s

Link <a href="https://en.wikipedia.org/wiki/M%C3%A1laga">here</a>!
Link [here](https://en.wikipedia.org/wiki/M%C3%A1laga)!

href 中不能有 unicode 字符,因为它是字符串格式的。 错误来自第 163 行中的html2text.HTML2Text.closeouttext = nochr.join(self.outtextlist),其中nochrunicode('')self.outtextlist 是标签部分的列表:

[u'Link ', '[', u'h\xe9r\xe9', '](https://en.wikipedia.org/wiki/Mlaga)', u'!', '\n', '']  

如您所见,包含 href 的项目不是 unicode 字符串。

这是因为在 html2text.HTML2Text.handle_tag 中,在函数 link_url 的第 440 行中,url 被格式化为字符串:']({url}{title})'.format(url=escape_md(url), title=title)
如果您将其更改为 unicode (u']({url}{title})'),您将在 self.outtextlist 中获得一个 unicode 字符串:

[u'Link ', '[', u'h\xe9r\xe9', u'](https://en.wikipedia.org/wiki/Ml\xe1ga)', u'!', '\n','']

u'Link &lt;a href="https://en.wikipedia.org/wiki/Mlága"&gt;héré&lt;/a&gt;!' 的输出将是:

Link [héré](https://en.wikipedia.org/wiki/Mlága)!

但是我不建议修改原始代码。一个可能的解决方案是继承HTML2Text 并覆盖link_url,但问题是link_url 是一个本地函数,因此您必须覆盖整个handle_tag 方法。

【讨论】:

  • 感谢您非常详细的见解 t.m.亚当!我使用引号和正则表达式来查找 URL 使其工作。奇怪的是,我似乎有一个文件的备份,其中 html2text 正确处理了一个“有问题的”url。无论如何,这行得通,所以谢谢你:)
猜你喜欢
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
相关资源
最近更新 更多