【问题标题】:Python html browsing Local url path issuePython html浏览本地url路径问题
【发布时间】:2021-03-31 04:59:25
【问题描述】:

我使用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)

在上面的代码中,它会创建一个这样的链接: &lt;a href="B_Folder/b1.html"&gt;stringCounter&lt;/a&gt; 所以问题是在浏览 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”,但始终无效。我无法为其添加绝对路径,因为它将迁移到其他一些根文件夹。谢谢!

【问题讨论】:

    标签: python html directory path


    【解决方案1】:

    相对路径 counter_path="../B_Folder" 应该可以工作。

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

    有关... 的更多示例,请参阅this answer to a Stack Exchange post

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 2013-11-25
      • 2011-04-10
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多