与空间建立适当的联系

2024-10-02 12:37:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了以下代码:

linkHTML = "<a href=\"page?q=%s\">click here</a>" % strLink

问题是,当strLink中有空格时,链接显示为

^{pr2}$

我可以用strLink.更换(“”,“+”)

但我相信还有其他的角色会导致错误。我试着用

urllib.quote(strLink)

但似乎没什么用。在

谢谢! 乔尔


Tags: 代码角色here链接错误pageurllibquote
2条回答

确保使用urllib.quote_plus(string[,safe])将空格替换为加号。在

urllib.quote_plus(string[, safe])

Like quote(), but also replaces spaces by plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.

来自http://docs.python.org/library/urllib.html#urllib.quote_plus

理想情况下你应该使用urllib.urlencode函数,并向它传递一系列键/值对,如{[“q”,“with space”],[“s”,“with space&other”]}等

除了quote_plus(*),您还需要对输出到HTML的任何文本进行HTML编码。否则,<&符号将被标记,可能会带来安全后果。(好的,您不会在URL中得到<,但是您肯定会得到&,所以只需要一个与HTML实体名匹配的参数名,而字符串就搞乱了。在

html= '<a href="page?q=%s">click here</a>' % cgi.escape(urllib.quote_plus(q))

*:实际上,普通的quote也可以;我不知道什么对您不起作用,但它是一种非常好的URL字符串编码方式。它将空格转换为%20,这也是有效的,在路径部分也是有效的。quote_plus是生成查询字符串的最佳选择,但在其他情况下,当有疑问时,quote是最安全的。在

相关问题 更多 >

    热门问题