Python

「ImportError: cannot import name 'quote' from 'urllib'」の対処法

Share this for your friends.

「ImportError: cannot import name 'quote' from 'urllib'」の対処法


ImportError: cannot import name 'quote' from 'urllib'って出ちゃった・・・


マルチバイトの文字列をURLパラメータにエンコードするときに便利な quote

しかしimportしようとしたら以下のエラーが出た。

ImportError: cannot import name 'quote' from 'urllib'


どうすれば回避できるのか。

そこで今回は「ImportError: cannot import name 'quote' from 'urllib'」の対処法について解説する。

この記事を書いている人


システムエンジニア、AIエンジニアと、IT業界で10年以上働いている中堅。PythonとSQLが得意。

記事を読むメリット

「ImportError: cannot import name 'quote' from 'urllib'」の対処法がわかり、importエラーに強くなる


「ImportError: cannot import name 'quote' from 'urllib'」のエラー

まずエラーはどのようにして起こるのか。

当該の ImportError: cannot import name 'quote' from 'urllib' を再現するとこうなる。

from urllib import quote

# ImportError: cannot import name 'quote' from 'urllib' (/usr/lib/python3.8/urllib/__init__.py)

# ---------------------------------------------------------------------------
# NOTE: If your import is failing due to a missing package, you can
# manually install dependencies using either !pip or !apt.

# To view examples of installing some common dependencies, click the
# "Open Examples" button below.
# ---------------------------------------------------------------------------


ImportError なので原因は、インポート対象が存在しない、もしくはインポートの指定方法が間違っているかだ。

ではどうすればよいのか。



「ImportError: cannot import name 'quote' from 'urllib'」の対処法

では「ImportError: cannot import name 'quote' from 'urllib'」にはどのように対処したらよいのか。


quote のインポートエラーが出る場合はimportの方法が間違っている

正しくインポートするには urllib ではなく urllib.parse からインポートする必要がある。

実際にやってみると以下のようになる。

from urllib.parse import quote

txt = "日本語"

print("txt:{}".format(txt))
print("quote_txt:{}".format(quote(txt)))

# txt:日本語
# quote_txt:%E6%97%A5%E6%9C%AC%E8%AA%9E



なんだ、これだけかー
どこかのサイトからコピペしたコードがエラーになったからって、焦ってはいけませんよー?
うう・・・



他にもPythonに関する記事もあるので、もし気になるものがあれば見てみて欲しい


Share this for your friends.

ITipsと同じようなブログを作る方法

ブログに興味がありますか?

もしブログに興味がある場合は↓このページ↓を参考にすれば、ITipsと同じ構成でブログを作ることができます

サーバー、ドメイン、ASPと【ブログに必要なものは全て】このページに書きました。
同じ構成でブログ作るのはいいけど、記事はマネしないでネ (TДT;)

ランキング参加中

にほんブログ村 IT技術ブログへ

他にもブログやSNSで紹介してくれると励みになります。

はてブのコメントで酷評されると泣きます(´;ω;`)

-Python
-

© 2024 ITips