【问题标题】:Redact and remove password from URL从 URL 中编辑和删除密码
【发布时间】:2018-04-04 22:43:00
【问题描述】:

我有一个这样的网址:

https://user:password@example.com/path?key=value#hash

结果应该是:

https://user:???@example.com/path?key=value#hash

我可以使用正则表达式,但我想将 URL 解析为高级数据结构,然后对该数据结构进行操作,然后序列化为字符串。

这可以用 Python 实现吗?

【问题讨论】:

    标签: python url-parsing


    【解决方案1】:

    您可以使用内置的urlparse 从网址中查询出密码。它在 Python 2 和 3 中都可用,但在不同的位置。

    Python 2import urlparse

    Python 3from urllib.parse import urlparse

    示例

    from urllib.parse import urlparse
    
    parsed = urlparse("https://user:password@example.com/path?key=value#hash")
    parsed.password # 'password'
    
    replaced = parsed._replace(netloc="{}:{}@{}".format(parsed.username, "???", parsed.hostname))
    replaced.geturl() # 'https://user:???@example.com/path?key=value#hash'
    

    另请参阅此问题:Changing hostname in a url

    【讨论】:

    • 不是一个很好的答案,如果一开始没有用户名和密码,这将返回类似https://None:???@example.com/ 的内容。
    • @Patrick 如果您认为应该提供更多信息,请随时留下您自己的答案,或提交对此答案的编辑请求。
    • @Patrick 喜欢这里的大多数答案,这显示了如何做被问到的事情。读者可以将其加工成综合代码。一个简单的 if 语句可以检查 parsed.passwordparsed.username 是否存在并相应地调整行为。
    猜你喜欢
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多