Python:获取 URL 路径部分

2023-12-03

如何从 url 获取特定路径部分?例如,我想要一个对此进行操作的函数:

http://www.mydomain.com/hithere?image=2934

并返回“这里”

或对此进行操作:

http://www.mydomain.com/hithere/something/else

并返回相同的东西(“hithere”)

我知道这可能会使用 urllib 或 urllib2 但我无法从文档中弄清楚如何仅获取路径的一部分。


提取 URL 的路径部分urlparse(Python 2.7):

import urlparse
path = urlparse.urlparse('http://www.example.com/hithere/something/else').path
print path
> '/hithere/something/else'

or urllib.parse(Python 3):

import urllib.parse
path = urllib.parse.urlparse('http://www.example.com/hithere/something/else').path).path
print(path)
> '/hithere/something/else'

将路径拆分为组件操作系统路径.split:

>>> import os.path
>>> os.path.split(path)
('/hithere/something', 'else')

dirname 和 basename 函数为您提供分割的两个部分;也许在 while 循环中使用 dirname :

>>> while os.path.dirname(path) != '/':
...     path = os.path.dirname(path)
... 
>>> path
'/hithere'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:获取 URL 路径部分 的相关文章

随机推荐