tags:

views:

26

answers:

2

Hello,

I have the following code in Python:

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

The problem is that when strLink has spaces in it the link shows up as

<a href="page?q=with space">click here</a>

I can use strLink.replace(" ","+")

But I am sure there are other characters which can cause errors. I tried using

urllib.quote(strLink)

But it doesn't seem to help.

Thanks! Joel

+2  A: 

Make sure you use the urllib.quote_plus(string[, safe]) to replace spaces with plus sign.

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 '/'.

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

Ideally you'd be using the urllib.urlencode function and passing it a sequence of key/value pairs like {["q","with space"],["s","with space & other"]} etc.

nvuono
A: 

As well as quote_plus(*), you also need to HTML-encode any text you output to HTML. Otherwise < and & symbols will be markup, with potential security consequences. (OK, you're not going to get < in a URL, but you definitely are going to get &, so just one parameter name that matches an HTML entity name and your string's messed up.

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

*: actually plain old quote is fine too; I don't know what wasn't working for you, but it is a perfectly good way of URL-encoding strings. It converts spaces to %20 which is also valid, and valid in path parts too. quote_plus is optimal for generating query strings, but otherwise, when in doubt, quote is safest.

bobince