【问题标题】:How to handle links containing space between them in Python如何在 Python 中处理它们之间包含空格的链接
【发布时间】:2016-01-08 01:53:46
【问题描述】:

我正在尝试从网页中提取链接,然后在我的网络浏览器中打开它们。我的 Python 程序能够成功提取链接,但某些链接之间有空格,无法使用 request module 打开。

例如example.com/A, B C 它不会使用请求模块打开。但如果我将其转换为example.com/A,%20B%20C,它将打开。 python中有没有一种简单的方法可以用%20填充空格?

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

我想将它们之间有空格的所有链接转换为上述格式。

【问题讨论】:

    标签: python url request broken-links


    【解决方案1】:

    urlencode实际上是带字典的,例如:

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

    取自How can I normalize a URL in python

    【讨论】:

    • 我正在使用类似 '%20'.join(line.split()) 的东西。你认为这是一个好的决定吗?
    • 好吧,这将处理空格:) 但我建议使用上面的 sn-p,因为它似乎工作得很好。 http url 以及其他字符列表也不支持逗号。这似乎可以正确处理它们。
    • 是的,我同意你的看法。非常感谢:)
    • 这在 python3 中不起作用,因为 urlparse 和 urllib 合并为一个,并且不需要编码为 Unicode,因为在 python 3 中每个字符串都被视为 unicode。查看我在此页面上的最后一篇文章。
    【解决方案2】:

    使用网址编码:

    import urllib
    urllib.urlencode(yourstring)
    

    【讨论】:

    • 我收到此错误TypeError: not a valid non-string sequence or mapping object
    【解决方案3】:

    @rofls 答案的 Python 3 工作解决方案。

    import urllib.parse as urlparse
    def url_fix(s):
        scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
        path = urlparse.quote(path, '/%')
        qs = urlparse.quote_plus(qs, ':&=')
        return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 2019-01-06
      相关资源
      最近更新 更多