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

问题描述 投票:0回答:8

我正在尝试确定 URL 的基础,或除页面和参数之外的所有内容。

我尝试使用 split,但是有没有比将其分成几部分更好的方法?

有什么方法可以删除最后一个

/
中的所有内容吗?

鉴于此:

http://127.0.0.1/asdf/login.php

我想要:

http://127.0.0.1/asdf/
python python-3.x
8个回答
41
投票

最好的方法是使用

urllib.parse

来自文档:

该模块的设计符合相关的互联网 RFC 统一资源定位器。它支持以下 URL 方案:

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:[email protected]: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"

22
投票

嗯,一方面,你可以使用

os.path.dirname
:

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

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

您可能还想查看

urllib.parse.urlparse
以进行更细粒度的解析;如果 URL 涉及查询字符串或哈希,您需要将其解析为片段,修剪解析返回的
path
组件,然后重新组合,以便修剪路径而不会丢失查询和哈希信息。

最后,如果您想在最后一个斜杠之后拆分组件,您可以使用 rsplit

maxsplit 执行
1
,并保留第一个组件:

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

9
投票

同意最好的方法是使用

urllib.parse

具体来说,您可以使用

urllib.parse.urlparse
分解 url,然后将除
scheme
netloc
之外的所有属性替换为空字符串。如果您想保留
path
属性(如您的问题中所示),您可以通过额外的字符串解析步骤来实现。下面的示例函数:

import urllib.parse
def base_url(url, with_path=False):
    parsed = urllib.parse.urlparse(url)
    path   = '/'.join(parsed.path.split('/')[:-1]) if with_path else ''
    parsed = parsed._replace(path=path)
    parsed = parsed._replace(params='')
    parsed = parsed._replace(query='')
    parsed = parsed._replace(fragment='')
    return parsed.geturl()

示例:

>>> base_url('http://127.0.0.1/asdf/login.php', with_path=True)
'http://127.0.0.1/asdf'
>>> base_url('http://127.0.0.1/asdf/login.php')
'http://127.0.0.1'

8
投票

使用 urllib 库的 Python3 有最短的解决方案(不知道是否最快):

from urllib.parse import urljoin

base_url = urljoin('http://127.0.0.1/asdf/login.php', '.')
# output: http://127.0.0.1/asdf/

请记住,urllib 库支持与 HTML 关键字兼容的 uri/url。这意味着以 '/' 结尾的 uri/url 意味着与没有像这里一样的不同 https://stackoverflow.com/a/1793282/7750840/:

base_url = urljoin('http://127.0.0.1/asdf/', '.')
# output: http://127.0.0.1/asdf/

base_url = urljoin('http://127.0.0.1/asdf', '.')
# output: http://127.0.0.1/

这是 python urllib 的链接:https://pythonprogramming.net/urllib-tutorial-python-3/


2
投票

当您使用 urlsplit 时,它会返回一个 SplitResult 对象:

from urllib.parse import urlsplit
split_url = urlsplit('http://127.0.0.1/asdf/login.php')
print(split_url)

>>> SplitResult(scheme='http' netloc='127.0.0.1' path='/asdf/login.php' query='' fragment='') 

您可以创建自己的 SplitResult() 对象并通过 urlunsplit 传递它。这段代码应该适用于多个 url 分割,无论它们的长度如何,只要您知道您想要的最后一个路径元素是什么。

from urllib.parse import urlsplit, urlunsplit, SplitResult

# splitting url:
split_url = urlsplit('http://127.0.0.1/asdf/login.php')

# editing the variables you want to change (in this case, path):    
last_element = 'asdf'   # this can be any element in the path.
path_array = split_url.path.split('/')

# print(path_array)
# >>> ['', 'asdf', 'login.php']

path_array.remove('') 
ind = path_array.index(last_element) 
new_path = '/' + '/'.join(path_array[:ind+1]) + '/'

# making SplitResult() object with edited data:
new_url = SplitResult(scheme=split_url.scheme, netloc=split_url.netloc, path=new_path, query='', fragment='')

# unsplitting:
base_url = urlunsplit(new_url)

1
投票

无需使用正则表达式,只需使用

rsplit()

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

1
投票

如果你使用python3,你可以使用urlparse和urlunparse。

In :from urllib.parse import urlparse, urlunparse

In :url = "http://127.0.0.1/asdf/login.php"

In :result = urlparse(url)

In :new = list(result)

In :new[2] = new[2].replace("login.php", "")

In :urlunparse(new)
Out:'http://127.0.0.1/asdf/'

0
投票

获取最右边出现的斜线;使用字符串切片通过原始字符串中的该位置。 +1 让您在最后得到最后的斜杠。

link = "http://127.0.0.1/asdf/login.php"
link[:link.rfind('/')+1]
© www.soinside.com 2019 - 2024. All rights reserved.