How to handle links containing a space between them in Python

I am trying to extract links from a web page and then open them in my web browser. My Python program can successfully extract links, but some links have spaces between them that cannot be opened with request module.

For example, example.com/A, B Cit will not be opened using the query module. But if I convert it to example.com/A,%20B%20C, it will open. Is there an easy way in python to fill in spaces with %20?

`http://example.com/A, B C` ---> `http://example.com/A,%20B%20C`

I want to convert all links that have spaces between them into the above format.

+4
source share
2 answers

urlencode really accepts a dictionary, for example:

>>> urllib.urlencode({'test':'param'})
'test=param'`

- :

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))

:

>>>url_fix('http://example.com/A, B C')    
'http://example.com/A%2C%20B%20C'

URL- python

+3

url:

import urllib
urllib.urlencode(yourstring)
+1

Source: https://habr.com/ru/post/1611049/


All Articles