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

前端 未结 2 2016
梦毁少年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:04

    Use urlparse.parse_qsl() to crack the query string. You can filter this in one go:

    params = [(k,v) for (k,v) in parse_qsl(parsed.query) if k != 'page']
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题