在写爬虫爬取下载链接来下载文件时,需要判断文件下载链接的后缀来命名文件,可以使用os库中获取文件名后缀的方法

完整下载链接:

import os

# 完整下载链接
link = "https://html/sm01.pdf"

# 使用os.path.splitext()获取路径和后缀
path, suffix = os.path.splitext(link)

print("路径:", path)  # 输出: 路径: https://html/sm01
print("后缀:", suffix)  # 输出: 后缀: .pdf

在这里插入图片描述

下载链接尾部片段:

import os

# 下载链接片段
link = "html/sm01.pdf"

# 使用os.path.splitext()获取路径和后缀
path, suffix = os.path.splitext(link)

print("路径:", path)  # 输出: 路径: html/sm01
print("后缀:", suffix)  # 输出: 后缀: .pdf

在这里插入图片描述

当然,也可以用来获取文件路径和文件后缀

更多推荐