Url 解析缺少片段 - Python

Url Parse is missing fragment - Python

我需要用给定采集路径的文件名保存一个文件。

给定一个 URL 我想解析它并提取文件名,这是我的代码...

我读取了一个 JSON 参数并将其提供给 Parse Url 函数。获取路径为字符串。

ParseUrl.py:

from urllib.parse import urlparse as up
a = up(jtp["AcquisitionPath"])    # => http://127.0.0.1:8000/Users/YodhResearch/Desktop/LongCtrl10min.tiff
print(a)
print(os.path.basename(a))

结果:

ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/Users/YodhResearch/Desktop/LongCtrl10min.tiff', params='', query='', fragment='')
[....]
TypeError: expected str, bytes or os.PathLike object, not ParseResult

如你所见,解析了URL,但是"LongCtrl10min.tiff"不在片段部分,而是全部在路径部分。为什么会这样?可能是因为 "AcquisitionPath" 是一个字符串并且 UrlParse 将所有内容识别为唯一路径?

编辑:

a.path 可以,我想知道为什么我没有把它放到片段部分。

这是另一个例子:

from urllib.parse import urlparse as up

string = "http://127.0.0.1:8000/GIULIO%20FERRARI%20FOLDER/Giulio%20_%20CSV/Py%20Script/sparse%20python/tiff_test.tiff_IDAnal#1_IDAcq#10_TEMP_.json"

a = up(string)
print(a)
print(os.path.basename(a))

结果:

ParseResult(scheme='http', netloc='127.0.0.1:8000', path='/GIULIO%20FERRARI%20FOLDER/Giulio%20_%20CSV/Py%20Script/sparse%20python/tiff_test.tiff_IDAnal', params='', query='', fragment='1_IDAcq#10_TEMP_.json')

看,现在它没有得到正确的片段应该是:"tiff_test.tiff_IDAnal#1_IDAcq#10_TEMP_.json"

解决方案:

片段需要'#'符号!感谢大家。

这里有两个问题:如何识别 URL 的组件,以及如何从这些组件创建所需的路径。


首先,您对片段的实际内容感到困惑。来自 RFC 3986:

The following are two example URIs and their component parts:

         foo://example.com:8042/over/there?name=ferret#nose
         \_/   \______________/\_________/ \_________/ \__/
          |           |            |            |        |
       scheme     authority       path        query   fragment
          |   _____________________|__
         / \ /                        \
         urn:example:animal:ferret:nose

该片段只是 # 之后的部分,而不是路径的整个最终部分。


其次,来自 urllib 模块的 urlparse() 函数 returns 一个 ParseResult 对象和来自 os.pathbasename() 方法想要一个str 作为参数。

您可能想要的是从 ParseResult 对象获取路径。您将通过 a.path 获得此信息(您通过 urlparse 提供的路径保存在 ParseResult-object 的属性 path 中)。

from urllib.parse import urlparse as up
a = up("http://127.0.0.1:8000/Users/YodhResearch/Desktop/LongCtrl10min.tiff")
print(os.path.basename(a.path))

这将输出:

LongCtrl10min.tiff

如果您还想包含片段,可以通过显式添加它来实现。片段保存在 ParseResult 对象的单独属性中,即 a.fragment 在您的情况下:

from urllib.parse import urlparse as up 
a = up("http://127.0.0.1:8000/Users/YodhResearch/Desktop/LongCtrl10min.tiff#anyfragment") 
print(os.path.basename(a.path) + "#" + a.fragment)                     

将输出:

LongCtrl10min.tiff#anyfragment