gpt4 book ai didi

python - 使用 python-markdown 检查图像 url

转载 作者:太空狗 更新时间:2023-10-30 00:57:39 25 4
gpt4 key购买 nike

在我正在创建的网站上,我正在使用 Python-Markdown格式化新闻文章。为了避免死链接和 HTTPS 页面上的 HTTP 内容问题,我要求编辑器将所有图像上传到站点,然后嵌入它们(我使用的是 Markdown 编辑器,我已经修补它以便于嵌入这些图像使用标准的 Markdown 语法)。

但是,我想在我的代码中强制执行无外部图像政策。

一种方法是编写一个正则表达式从 Markdown 源代码中提取图像 URL,或者甚至通过 Markdown 渲染器运行它并使用 DOM 解析器提取所有 src来自 img 的属性标签。

但是,我很好奇是否有某种方法可以挂接到 Python-Markdown 以在解析期间提取所有图像链接或执行自定义代码(例如,如果链接是外部链接则引发异常)。

最佳答案

一种方法是拦截 <img>在 Markdown 解析和构造它之后的较低级别的节点:

import re
from markdown import Markdown
from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE

RE_REMOTEIMG = re.compile('^(http|https):.+')

class CheckImagePattern(ImagePattern):

def handleMatch(self, m):
node = ImagePattern.handleMatch(self, m)
# check 'src' to ensure it is local
src = node.attrib.get('src')
if src and RE_REMOTEIMG.match(src):
print 'ILLEGAL:', m.group(9)
# or alternately you could raise an error immediately
# raise ValueError("illegal remote url: %s" % m.group(9))
return node

DATA = '''
![Alt text](/path/to/img.jpg)
![Alt text](http://remote.com/path/to/img.jpg)
'''

mk = Markdown()
# patch in the customized image pattern matcher with url checking
mk.inlinePatterns['image_link'] = CheckImagePattern(IMAGE_LINK_RE, mk)
result = mk.convert(DATA)
print result

输出:

ILLEGAL: http://remote.com/path/to/img.jpg
<p><img alt="Alt text" src="/path/to/img.jpg" />
<img alt="Alt text" src="http://remote.com/path/to/img.jpg" /></p>

关于python - 使用 python-markdown 检查图像 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com