gpt4 book ai didi

python - 在 Python 中将 & 转换为 &

转载 作者:行者123 更新时间:2023-12-02 05:32:17 25 4
gpt4 key购买 nike

我正在使用 Python 开发一个简单的爬虫。目的是创建一个 sitemap.xml。(你可以在这里找到真正的 alpha 版本:http://code.google.com/p/sitemappy/)我注意到如果我使用包含非 HTML 实体(例如 &)的 URL 生成 xml,则 xml 不会验证并且不会被 Google 网站管理员工具接受。有没有一种快速的方法来对 URL 的查询字符串部分进行编码?

谢谢!

马特奥

最佳答案

cgi.escape救援:

cgi.escape(s[, quote])

Convert the characters '&', '<' and '>' in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the optional flag quote is true, the quotation mark character ('"') is also translated; this helps for inclusion in an HTML attribute value, as in . If the value to be quoted might include single- or double-quote characters, or both, consider using the quoteattr() function in the xml.sax.saxutils module instead.

快速交互式检查:

>>> import cgi
>>> cgi.escape('<&>')
'&lt;&amp;&gt;'
>>>

关于python - 在 Python 中将 & 转换为 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1650160/

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