12
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonにおける相対urlの処理

Posted at

pythonでos.pathというとても便利なクラスがあるのですが、絶対パスと相対パスを結合する時に、

# abs_path = "/usr/hoge/", rel_path = "./poyo/"
path.normpath(path.join(abs_path, rel_path))
# "/usr/hoge/poyo"

とよくやります。これ、urlでも使えるなーと思い、

# abs_path = "http://hoge/", rel_path = "./poyo/"
path.normpath(path.join(abs_url, rel_url) 
# "http:/hoge/poyo/"

としていたら、urlが開けないと怒られました。それでちょっと悩んだ訳ですが、理由は簡単で "http://hoge/" というurlが path.normpath で "http:/hoge" に変換されていたんですね。pathはファイルシステムのパスのためのクラスなので、こういう仕様になっていたわけです。
urlの結合には urlparseクラスのurljoinメソッドを使うそうです。

# abs_path = "http://hoge/", rel_path = "./poyo/"
urlparse.urljoin(abs_url, rel_url)
# "http://hoge/poyo/"
12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?