url - How to handle links containing space between them in Python -
i trying extract links webpage , open them in web browser. python program able extract links, links have spaces between them cannot open using request module
.
for example example.com/a, b c
not open using request module. if convert example.com/a,%20b%20c
open. there simple way in python fill spaces %20
?
`http://example.com/a, b c` ---> `http://example.com/a,%20b%20c`
i want convert links have spaces between them above format.
urlencode
takes dictionary, example:
>>> urllib.urlencode({'test':'param'}) 'test=param'`
you need this:
import urllib import urlparse def url_fix(s, charset='utf-8'): if isinstance(s, unicode): s = s.encode(charset, 'ignore') scheme, netloc, path, qs, anchor = urlparse.urlsplit(s) path = urllib.quote(path, '/%') qs = urllib.quote_plus(qs, ':&=') return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
then:
>>>url_fix('http://example.com/a, b c') 'http://example.com/a%2c%20b%20c'
Comments
Post a Comment