我是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()中犯了一个根本性的错误?
解决方法:
urllib.urlencode需要一个映射或序列,每个映射或序列包含两个项目.从docs中可以看出
在您的代码中,您需要执行以下操作:
urllib.urlencode({'Agent': UserAgent})