Michelle Moya
Michelle Moya

Reputation: 39

How to join a string to a URL in Python?

I am trying to join a string in a URL, but the problem is that since it's spaced the other part does not get recognized as part of the URL.

Here would be an example:

import urllib
import urllib2
website = "http://example.php?id=1 order by 1--"
request = urllib2.Request(website)
response = urllib2.urlopen(request)
html = response.read()

The "order by 1--" part is not recognized as part of the URL.

Upvotes: 1

Views: 556

Answers (2)

zmo
zmo

Reputation: 24802

You should better use urllib.urlencode or urllib.quote:

website = "http://example.com/?" + urllib.quote("?id=1 order by 1--")

or

website = "http://example.com/?" + urllib.urlencode({"id": "1 order by 1 --"})

and about the query you're trying to achieve:

I think you're forgetting a ; to end the first query.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799240

Of course not. Spaces are invalid in a query string, and should be replaced by +.

http://example.com/?1+2+3

Upvotes: 2

Related Questions