通过 URL 重新映射,我的意思是更改实际 HTML 文档中的所有“href”、“src”、“action”等。
是否有任何 python 库可以执行此类 URL 重新映射?
在 python Web 服务器应用程序(基于 Tornado )上,我希望能够根据某些条件修改我服务器的 HTML 代码。
想象一下,我从磁盘上读取了此 HTML,但我需要替换所有链接并...以指向此子域/域和路径或该子域/域和路径。
假设我不想使用模板重写磁盘上的所有 HTML(将标签放入其中并在运行时替换标签),为了简单起见,也可以假设我没有外部链接(就像我切勿链接到 google.com [需要条件重新映射])。
最佳答案
据我所知,没有这样的库,但是你可以使用一些html解析库,例如 lxml或BeautifulSoup与 urlparse
一起标准 Python 模块。我更喜欢使用 lxml
和 XPath .
例如,我们将 StackOverflow 页面保存为 doc.html
,并且我们想要对包含 href
、src
的节点执行某些操作,操作
:
import urlparse
import lxml.html
with open('doc.htm') as f:
doc = lxml.html.parse(f)
for el in doc.xpath('//*[@href | @src | @action]'):
tag = el.tag
href = el.get('href', '')
if not href:
continue
# not really need to check for '/' when using urljoin, but this is just example
if href.startswith('/'):
el.attrib['href'] = urlparse.urljoin('http://stackoverflow.com/', href)
# then get string representation of tree back
result = lxml.html.tostring(doc)
在此示例中,我仅使用 urlparse.urljoin
将以“/”开头的相对 href
转换为绝对值,并且并未使用 XPath 结果中的所有元素。但您可以根据需要对其进行自定义。
关于python - HTML 内部,Python 中的 URL 重映射库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8953995/