首页 > 解决方案 > Python html浏览本地url路径问题

问题描述

我使用python生成html页面。在根文件夹下,我创建了两个文件夹 A 和 B。在 B 中有 b1.html、b2.html 等。在文件夹 A 中,我有 A1.html 和 A2.html 等等。在 A1.html 中,当生成这样的 html 时,我根据 A1.html 中出现的关键字 bx 创建到 bx.html 的链接。

例如:

    stringsCounterNames = re.findall('\[([A-Z].*?)\]',line) #find the keywords
    stringsCounterNames = list(dict.fromkeys(stringsCounterNames)) #remove duplicates
    counter_path="B_Folder"
    if (len(stringsCounterName)>0):

        for stringCounter in stringsCounterNames:
            targetStr=counter_dic[stringCounter]
            target = '<a href="' + counter_path + '/' + targetStr + '.html">' + stringCounter + '<a>'
            line = re.sub(stringCounter, target, line)
            print(line)

在上面的代码中,它将创建一个这样的链接: <a href="B_Folder/b1.html">stringCounter</a> 所以问题是在浏览 A1.html 时,单击该链接,它会转到:File:rootFolder/A_Folder/B_Folder/b1.html,因此该链接永远不会起作用,因为 A_Folder 和 B_Folder 都是 rootFolder 下的子文件夹。我可以将 B_Folder 移到 A_Folder 下来解决问题,但我想让文件井井有条。有没有办法轻松解决这个问题?我尝试将“counter_path”更改为“..B_Folder”或“.B_Folder”,但始终无效。我无法为其添加绝对路径,因为它将迁移到其他一些根文件夹。谢谢!

标签: pythonhtmldirectorypath

解决方案


相对路径counter_path="../B_Folder"应该有效。

您的建议很接近,但两者..B_Folder都是.B_Folder有效的文件夹名称;因此,相对路径仍然是root/A_Folder/..B_Folderor root/A_Folder/.B_Folder。但是,文件夹名称...分别指父文件夹和当前文件夹。添加..为单独的文件夹(因此将路径更改为root/A_Folder/../B_Folder)有效:从root/A_Folder,导航到..更改路径root,您可以从中导航到B_Folder

有关 和 的更多示例...请参阅Stack Exchange 帖子的此答案


推荐阅读