如何在 Python 中获取 URL 的基础?

新手上路,请多包涵

我正在尝试确定 URL 的基础,或者除页面和参数之外的所有内容。我试过使用 split,但有没有比将它分成几块更好的方法?有没有办法可以删除最后一个“/”中的所有内容?

鉴于此:http: //127.0.0.1/asdf/login.php

我想:http: //127.0.0.1/asdf/

原文由 Brendan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 402
2 个回答

好吧,首先,您可以使用 os.path.dirname

 >>> os.path.dirname('http://127.0.0.1/asdf/login.php')
'http://127.0.0.1/asdf'

它不是明确用于 URL,但它恰好适用于它们(甚至在 Windows 上),它只是不留下尾部斜杠(您可以自己将其添加回去)。

您可能还想查看 urllib.parse.urlparse 以获得更细粒度的解析;如果 URL 涉及查询字符串或散列,您希望将其解析成多个部分,修剪 path 解析返回的组件,然后重新组合,这样路径就可以在不丢失查询和散列信息的情况下被修剪。

最后,如果你想在最后一个斜线之后拆分组件,你可以做一个 rsplitmaxsplit1 并保留第一个组件:

 >>> 'http://127.0.0.1/asdf/login.php'.rsplit('/', 1)[0]
'http://127.0.0.1/asdf'

原文由 ShadowRanger 发布,翻译遵循 CC BY-SA 3.0 许可协议

最好的方法是使用 urllib.parse

从文档:

该模块的设计旨在与相对统一资源定位器上的 Internet RFC 相匹配。 It supports the following URL schemes: file , ftp , gopher , hdl , http , https , imap , mailto , mms , news , nntp , prospero , rsync , rtsp , rtspu , sftp , shttp , sip , sips , snews , svn , svn+ssh , telnet , wais , ws , wss

您想使用 urlspliturlunsplit 做这样的事情:

 from urllib.parse import urlsplit, urlunsplit

split_url = urlsplit('http://127.0.0.1/asdf/login.php?q=abc#stackoverflow')

# You now have:
# split_url.scheme   "http"
# split_url.netloc   "127.0.0.1"
# split_url.path     "/asdf/login.php"
# split_url.query    "q=abc"
# split_url.fragment "stackoverflow"

# Use all the path except everything after the last '/'
clean_path = "".join(split_url.path.rpartition("/")[:-1])

# "/asdf/"

# urlunsplit joins a urlsplit tuple
clean_url = urlunsplit(split_url)

# "http://127.0.0.1/asdf/login.php?q=abc#stackoverflow"

# A more advanced example
advanced_split_url = urlsplit('http://foo:bar@127.0.0.1:5000/asdf/login.php?q=abc#stackoverflow')

# You now have *in addition* to the above:
# advanced_split_url.username   "foo"
# advanced_split_url.password   "bar"
# advanced_split_url.hostname   "127.0.0.1"
# advanced_split_url.port       "5000"

原文由 dalanmiller 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题