You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中提取URL顶级域名(如.com)的字符串方法需求

提取URL顶级域名的Python方法

直接用split(".")的问题在于如果URL里包含多个点(比如https://sub.stackoverflow.co.uk这类带多级后缀的域名),结果会不准确。这里提供两种更可靠的实现方式:

方法一:用urllib.parse解析后处理

先解析出完整域名,再拆分提取顶级后缀:

from urllib.parse import urlparse

url = "https://stackoverflow.com/questions/ask"
parsed_url = urlparse(url)
# 获取完整域名部分,比如这里得到 stackoverflow.com
domain = parsed_url.netloc
# 拆分域名后取最后一段,再加上前缀点
tld = "." + domain.split(".")[-1]
print(tld)  # 输出结果:.com

方法二:用专门库处理复杂后缀(可选)

如果需要处理.co.uk、.com.cn这类多段顶级域名,推荐用tldextract库(需提前安装:pip install tldextract):

import tldextract

url = "https://stackoverflow.com/questions/ask"
extracted = tldextract.extract(url)
tld = "." + extracted.suffix
print(tld)  # 输出结果:.com

注意事项

  • 如果URL没有www前缀或协议头(比如stackoverflow.com/questions/ask),urlparse依然能正确提取域名部分,只要格式规范
  • 单纯的split(".")仅适用于单段顶级域名场景,遇到多段后缀会出错

内容的提问来源于stack exchange,提问作者J.B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:27:22