正确地对用户代理进行URL编码

3

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

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() 时犯了一些基本错误?

2个回答

7

urllib.urlencode函数需要一个包含两个元素的映射(mapping)或序列(sequence),具体信息可以参考文档

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

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

该死,我就知道一定是什么简单的东西。谢谢你。 - Basic

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.

如果你还不知道,可以查看dir(urllib)和dir(urllib.urlencode)。dir()可以让未知的变得已知;help()可以让已知的变得更加清晰。 - verbsintransit
我并不感谢,因为我熟悉许多其他编程语言,但需要在我的新xbmc媒体中心中使用Python来组合一些东西 - 所以我只有大约3小时的经验 :) 实际上,我已经成功地让某些东西运行了 - 这是一种非常强大而简洁的语言。 - Basic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接