问题:Python:导入urllib.quote

我想用urllib.quote()。但是python(python3)找不到模块。假设我有以下代码行:

print(urllib.quote("châteu", safe=''))

如何导入urllib.quote?

import urllibimport urllib.quote两者都给

AttributeError: 'module' object has no attribute 'quote'

令我困惑的urllib.request是可以通过以下方式访问import urllib.request

I would like to use urllib.quote(). But python (python3) is not finding the module. Suppose, I have this line of code:

print(urllib.quote("châteu", safe=''))

How do I import urllib.quote?

import urllib or import urllib.quote both give

AttributeError: 'module' object has no attribute 'quote'

What confuses me is that urllib.request is accessible via import urllib.request


回答 0

在Python 3.x中,您需要导入urllib.parse.quote

>>> import urllib.parse
>>> urllib.parse.quote("châteu", safe='')
'ch%C3%A2teu'

根据Python 2.x urllib模块文档

注意

urllib模块已经被分成部分和更名在Python 3 urllib.requesturllib.parse,和urllib.error

In Python 3.x, you need to import urllib.parse.quote:

>>> import urllib.parse
>>> urllib.parse.quote("châteu", safe='')
'ch%C3%A2teu'

According to Python 2.x urllib module documentation:

NOTE

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.


回答 1

如果您需要同时处理Python 2.x和3.x,则可以捕获异常并加载替代项。

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

您还可以使用python兼容性包装器6来处理此问题。

from six.moves.urllib.parse import quote

If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.

try:
    from urllib import quote  # Python 2.X
except ImportError:
    from urllib.parse import quote  # Python 3+

You could also use the python compatibility wrapper six to handle this.

from six.moves.urllib.parse import quote

回答 2

urllib在Python3中进行了一些更改,现在可以从parse子模块中导入

>>> from urllib.parse import quote  
>>> quote('"')                      
'%22'                               

urllib went through some changes in Python3 and can now be imported from the parse submodule

>>> from urllib.parse import quote  
>>> quote('"')                      
'%22'                               

回答 3

这就是我在不使用异常的情况下的处理方式。

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。