“模块”没有属性“ urlencode”

问题:“模块”没有属性“ urlencode”

当我尝试遵循与URL编码相关的Python Wiki的示例时

>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()

在第二行引发错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'urlencode'

我想念什么?

When I try to follow the Python Wiki’s example related to URL encoding:

>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()

An error is raised on the second line:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'urlencode'

What am I missing?


回答 0

urllib已在拆分Python 3

urllib.urlencode()功能是现在urllib.parse.urlencode()

urllib.urlopen()现在的功能urllib.request.urlopen()

urllib has been split up in Python 3.

The urllib.urlencode() function is now urllib.parse.urlencode(),

the urllib.urlopen() function is now urllib.request.urlopen().


回答 1

import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
import urllib.parse
urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

回答 2

您使用Python 2文档,但使用Python 3编写程序。

You use the Python 2 docs but write your program in Python 3.