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

Python 正确地对用户代理进行url编码,python,string,escaping,urlencode,Python,String,Escaping,Urlencode,我是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;

我是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 . . .
Mozilla/5.0(Windows;U;Windows NT 5.1;en-GB;rv:1.9.0.3 Gecko/2008092417 Firefox/3.0.3
回溯(最近一次呼叫最后一次):
文件“D:\Source\SomePath\test.py”,第7行,在
打印urllib.urlencode(用户代理)
文件“C:\Python26\lib\urllib.py”,第1254行,urlencode
提高打字错误
TypeError:不是有效的非字符串序列或映射对象
按任意键继续。

我只能假设,尽管
用户代理
打印正确,但我要么在输入过程中丢失了一些字符串转义选项,要么在
urllib.urlencode()

urllib.urlencode
方面犯了一个根本性的错误。正如在

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

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

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()让大家知道未知的东西。我没有再次感谢你。我熟悉很多其他语言,但需要在Python中为我的新xbmc媒体中心集成一些东西-所以我总共有大约3个小时的经验:)我实际上已经设法让一些东西工作了-这是一种非常强大和简洁的语言