在Python中隔离列表中URL的域

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

我需要一个字符串方法来隔离Python中URL的域。就像在

“https://stackoverflow.com/questions/ask”

我只需要隔离“.com”,之后或之前没有任何内容。

我尝试了一些天真的东西:

domain = URL.split(".")
python string list security
1个回答
0
投票

使用标准库的 URL 解析器 (

urllib.parse
) 提取主机名,然后在
.
上拆分以检索 TLD:

import urllib.parse

url = "https://stackoverflow.com/questions/ask"
hostname = urllib.parse.urlparse(url).hostname
tld = hostname.split(".")[-1]

>>> print(tld)
'com'
© www.soinside.com 2019 - 2024. All rights reserved.