Python:导入 urllib.quote
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31827012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Importing urllib.quote
提问by imrek
I would like to use urllib.quote()
. But python (python3) is not finding the module.
Suppose, I have this line of code:
我想用urllib.quote()
. 但是 python (python3) 没有找到模块。假设,我有这行代码:
print(urllib.quote("chateu", safe=''))
How do I import urllib.quote?
如何导入 urllib.quote?
import urllib
or
import urllib.quote
both give
import urllib
或者
import urllib.quote
都给
AttributeError: 'module' object has no attribute 'quote'
What confuses me is that urllib.request
is accessible via import urllib.request
让我困惑的urllib.request
是可以通过import urllib.request
采纳答案by falsetru
In Python 3.x, you need to import urllib.parse.quote
:
在 Python 3.x 中,您需要导入urllib.parse.quote
:
>>> import urllib.parse
>>> urllib.parse.quote("chateu", 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 tourllib.request
,urllib.parse
, andurllib.error
.
笔记
该
urllib
模块已经被分成部分和更名在Python 3urllib.request
,urllib.parse
,和urllib.error
。
回答by Justin Fay
urllib went through some changes in Python3 and can now be imported from the parse submodule
urllib 在 Python3 中进行了一些更改,现在可以从 parse 子模块导入
>>> from urllib.parse import quote
>>> quote('"')
'%22'
回答by eandersson
If you need to handle both Python 2.x and 3.x you can catch the exception and load the alternative.
如果您需要同时处理 Python 2.x 和 3.x,您可以捕获异常并加载替代项。
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 sixto handle this.
您还可以使用 python 兼容性包装器6来处理此问题。
from six.moves.urllib.parse import quote
回答by Yutenji
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