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

Python图片识别AI开发:如何自动提取URL末尾文件名避免用户重复输入

自动提取URL文件名的实现方案

核心逻辑

我们可以通过URL解析模块自动提取文件名,完全省去用户手动输入的步骤,推荐使用Python标准库的urllib.parse+os.path实现,兼容性优于直接字符串分割,可自动过滤URL后的查询参数、锚点等冗余内容。

具体修改点

  1. 新增两个依赖导入(如果之前没导入的话)
from urllib.parse import urlparse
import os
  1. 删除原有要求用户输入文件名的代码段,替换为自动提取逻辑
# 解析URL获取路径部分,过滤查询参数、锚点
url_path = urlparse(imageInput).path
# 提取路径最后一段作为文件名
imageEnding = os.path.basename(url_path)
# 兼容URL末尾为/的异常场景,避免空文件名报错
if not imageEnding:
    imageEnding = "temp_download_image.jpg"

修改后完整可运行代码

import urllib.request
from urllib.parse import urlparse
import os
import tensorflow as tf
from tensorflow import keras
import numpy as np
import time

# 此处需提前定义你的全局变量:img_height、img_width、class_names、model
def ImageRecognizer():
    print("########################################")
    print()
    print("请输入图片URL:")
    print()
    imageInput = input("")

    try:
        urllib.request.urlopen(imageInput)
    except: 
        print("URL无法访问,请重新输入")
        ImageRecognizer()

    # 自动提取文件名逻辑
    url_path = urlparse(imageInput).path
    imageEnding = os.path.basename(url_path)
    if not imageEnding:
        imageEnding = "temp_image.jpg"

    sunflower_url = imageInput
    sunflower_path = tf.keras.utils.get_file(imageEnding, origin=sunflower_url)

    img = keras.preprocessing.image.load_img(
        sunflower_path, target_size=(img_height, img_width)
    )
    img_array = keras.preprocessing.image.img_to_array(img)
    img_array = tf.expand_dims(img_array, 0)

    predictions = model.predict(img_array)
    score = tf.nn.softmax(predictions[0])

    print(
        "该图片最可能属于分类 {},置信度为 {:.2f}%。"
        .format(class_names[np.argmax(score)], 100 * np.max(score))
    )
    time.sleep(2)

简化版实现(仅适用于无参数的纯路径URL)

如果你能确保所有输入的URL都不携带?开头的查询参数和#开头的锚点,也可以用更简单的字符串分割方法:

imageEnding = imageInput.split('/')[-1]

该方法代码更少,但兼容性较差,遇到带参数的URL会提取到错误的文件名,不推荐正式环境使用。

内容的提问来源于stack exchange,提问作者Leo_001

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:27:02