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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:36:27  来源:igfitidea点击:

Python: Importing urllib.quote

pythonpython-3.ximporturllib

提问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 urllibor import urllib.quoteboth give

import urllib或者 import urllib.quote都给

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

What confuses me is that urllib.requestis 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 urllibmodule documentation:

根据Python 2.xurllib模块文档

NOTE

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

笔记

urllib模块已经被分成部分和更名在Python 3 urllib.requesturllib.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