在我创建的一个网站上,我使用Python-Markdown来格式化新闻帖子。为了避免死链接和HTTP-content-on-HTTPS-page的问题,我要求编辑器将所有图片上传到站点,然后嵌入它们(我使用的是一个标记编辑器,我已经对其打了补丁,以便使用标准标记语法轻松嵌入这些图像)。
但是,我想在我的代码中强制执行无外部映像策略。
一种方法是编写正则表达式来从markdown源代码中提取图像src,或者甚至通过markdown渲染器运行它,然后使用DOM解析器从img标记中提取所有URL属性。
然而,我很好奇是否有某种方法可以连接到Python-Markdown来提取所有图像链接或在解析过程中执行自定义代码(例如,如果链接是外部的,则引发异常)。
发布于 2011-05-12 07:48:27
一种方法是在Markdown解析并构造<img>节点之后,在较低的级别拦截它:
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 = '''


'''
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>发布于 2019-02-28 15:40:38
使用Python 3和Python-Mardown 3更新
import re
from markdown import Markdown
from markdown.inlinepatterns import Pattern, IMAGE_LINK_RE
RE_REMOTEIMG = re.compile('^(http|https):.+')
class CheckImagePattern(Pattern):
def handleMatch(self, m):
node = Pattern.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 = '''


'''
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希望它是有用的!
https://stackoverflow.com/questions/5930542
复制相似问题