Is there a better way to write this URL Manipulation in Python?

前端 未结 2 2310
梦毁少年i
梦毁少年i 2021-02-20 15:42

I\'m curious if there\'s a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more py

2条回答
  •  花落未央
    2021-02-20 16:05

    I've created a small helper class to represent a url in a structured way:

    import cgi, urllib, urlparse
    
    class Url(object):
        def __init__(self, url):
            """Construct from a string."""
            self.scheme, self.netloc, self.path, self.params, self.query, self.fragment = urlparse.urlparse(url)
            self.args = dict(cgi.parse_qsl(self.query))
    
        def __str__(self):
            """Turn back into a URL."""
            self.query = urllib.urlencode(self.args)
            return urlparse.urlunparse((self.scheme, self.netloc, self.path, self.params, self.query, self.fragment))
    

    Then you can do:

    u = Url(url)
    del u.args['page']
    url = str(u)
    

    More about this: Web development peeve.

提交回复
热议问题