gpt4 book ai didi

python - LXML 的 etree.tostring 在链接 href 属性中转义 url

转载 作者:数据小太阳 更新时间:2023-10-29 02:12:11 29 4
gpt4 key购买 nike

当使用 LXML 解析 html 文档,然后使用 etree.tostring() 时,我注意到链接中的 & 符号被转换为 html 转义实体。

这会破坏链接,原因很明显。这是问题的一个简单的独立示例:

>>> from lxml import etree
>>> parser = etree.HTMLParser()
>>> tree = etree.fromstring("""<a href="https://www.example.com/?param1=value1&param2=value2">link</a>""", parser)
>>> etree.tostring(tree)
'<html><body><a href="https://www.example.com/?param1=value1&amp;param2=value2">link</a></body></html>'

我希望输出是:

<html><body><a href="https://www.example.com/?param1=value1&param2=value2">link</a></body></html>

最佳答案

尽管 & 编码应该是 standard way .如果您确实出于某些原因需要避免转换,那么您可以这样做:

第 1 步。 找到一个不应该存在于您的 html 源代码中的唯一字符串。如果您确信“ANDamp;”,您可以简单地使用 ANDamp; 作为您的 reserved_amp 变量。字符串不会出现在您的 html 源代码中。否则,您可能会考虑生成随机字母并检查以确保该字符串不存在于您的 html 源代码中:

>>> import random
>>> import string
>>> length = 15 #increase the length if it's still seems to be collide
>>> reserved_amp = "&amp;"
>>> html = """<a href="https://www.example.com/?param1=value1&param2=value2">link</a>"""
>>> while reserved_amp in [html, "&amp;"]:
... reserved_amp = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length)) + "amp;" #amp; is for you easy to spot on
...
>>> print reserved_amp
2eya6oywxg5z7q5amp;

第 2 步。在解析之前替换所有出现的 &:

>>> html = html.replace("&", reserved_amp)
>>> html
'<a href="https://www.example.com/?param1=value12eya6oywxg5z7q5amp;param2=value2">link</a>'
>>>

第 3 步。仅当您需要原始表单时才将其替换回来:

>>> from lxml import etree
>>> parser = etree.HTMLParser()
>>> tree = etree.fromstring(html, parser)
>>> etree.tostring(tree).replace(reserved_amp, "&")
'<html><body><a href="https://www.example.com/?param1=value1&param2=value2">link</a></body></html>'
>>>

[更新]:

reserved_amp 末尾的冒号是安全 guard

如果我们生成这样的 reserved_amp 会怎么样?

ampXampXampXampX + amp;

而html包含:

yyYampX&

它将以这种形式编码:

yyYampXampXampXampXampXamp;

不过,由于 冒号 安全防护,不可能返回/解码错误的反转结果,如 yy&YampX(原来是 yyYampX&)最后一个字符是一个非 ASCII 字母,永远不会从上面的 string.ascii_lowercase + string.digits 生成为 reserved_amp

因此,确保随机数不使用冒号(或其他非 ASCII 字符),然后将其附加在末尾(必须是最后一个字符)将无需担心 yyYampX& 恢复为yy&YampX 陷阱。

关于python - LXML 的 etree.tostring 在链接 href 属性中转义 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610365/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com