【问题标题】:Is there a python function to replace absolute urls with relative url paths?是否有 python 函数用相对 url 路径替换绝对 url?
【发布时间】:2017-05-18 08:05:31
【问题描述】:

我正在抓取一个网站并保存选定的页面以供离线浏览。当然,页面之间的链接被破坏了,所以我想对此做点什么。在 python 中是否有一种简单的方法可以在不重新发明轮子的情况下将这样的 url 路径相对化:

/folder1/folder2/somepage.html    becomes---->   folder2/somepage.html
/folder1/otherpage.html           becomes---->   ../otherpage.html

我知道该函数需要两个 url 路径来确定相对路径,因为链接资源的路径是相对于它出现的页面的。

【问题讨论】:

标签: python relative-url


【解决方案1】:

较新的pathlib(仅在副本中简要提及)也适用于网址:

from pathlib import Path

abs_p = Path('https://docs.python.org/3/library/pathlib.html')
rel_p = abs_p.relative_to('https://docs.python.org/3/')
print(rel_p)  # library/pathlib.html

【讨论】:

  • 谢谢!这看起来很有希望,但是我忘了提到我正在使用 python 2.7,因为这是安装在 mac osx 上的版本,我希望它是可移植的。如果不出意外,我可能会查看源代码并选择我需要的部分,假设源代码在 2.7 中工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2015-01-24
  • 2015-09-20
  • 1970-01-01
  • 2011-05-25
相关资源
最近更新 更多