3

我是 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()?

4

2 回答 2

7

urllib.urlencode期望每个具有两个项目的映射或序列。如文档中所示

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

urllib.urlencode({'Agent': UserAgent})
于 2012-11-14T00:55:57.907 回答
2

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

>>> 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.
于 2012-11-14T00:57:10.687 回答