【问题标题】:Correctly url encoding a user agent正确地对用户代理进行 url 编码
【发布时间】:2012-11-14 00:50:33
【问题描述】:

我是 Python 新手,似乎遇到了问题。我正在尝试对用户代理字符串进行 urlencode...

import urllib

UserAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3'
print 'Agent: ' + UserAgent
print urllib.urlencode(UserAgent)

这会导致...

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3
Traceback (most recent call last):
  File "D:\Source\SomePath\test.py", line 7, in <module>
    print urllib.urlencode(UserAgent)
  File "C:\Python26\lib\urllib.py", line 1254, in urlencode
    raise TypeError
TypeError: not a valid non-string sequence or mapping object
Press any key to continue . . .

我只能假设虽然UserAgent 打印正确,但我要么在输入的过程中遗漏了一些字符串转义选项,要么在urllib.urlencode() 方面犯了一个根本性错误?

【问题讨论】:

    标签: python string escaping urlencode


    【解决方案1】:

    urllib.urlencode 需要一个映射或序列,每个都有两个项目。可以在docs中看到

    在您的代码中,您需要执行以下操作:

    urllib.urlencode({'Agent': UserAgent})
    

    【讨论】:

    • 该死,我就知道这一定很简单。谢谢
    【解决方案2】:

    Wessie 打败了我。为了将来参考,您也可以这样做:

    >>> help(urllib.urlencode)
    Help on function urlencode in module urllib:
    
    urlencode(query, doseq=0)
        Encode a sequence of two-element tuples or dictionary into a URL query string.
    
        If any values in the query arg are sequences and doseq is true, each
        sequence element is converted to a separate parameter.
    
        If the query arg is a sequence of two-element tuples, the order of the
        parameters in the output will match the order of parameters in the
        input.
    

    【讨论】:

    • NP。另外,如果您还不了解它,请查看 dir(urllib) 和 dir(urllib.urlencode)。 dir() 使未知的未知数已知; help() 使已知的未知数已知。
    • 我没有再次感谢。我熟悉许多其他语言,但需要在 Python 中为我的新 xbmc 媒体中心拼凑一些东西——所以我总共有大约 3 小时的经验 :) 我实际上已经设法让一些东西工作了- 这是一种非常强大且简洁的语言
    猜你喜欢
    • 2011-06-12
    • 2022-03-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多