使用python-markdown检查图片链接

7 投票
2 回答
3199 浏览
提问于 2025-04-16 17:15

在我创建的网站上,我使用了Python-Markdown来格式化新闻帖子。为了避免出现死链接和在HTTPS页面上使用HTTP内容的问题,我要求编辑们将所有图片上传到网站,然后再嵌入这些图片(我使用的是一个经过修改的markdown编辑器,可以方便地使用标准的markdown语法来嵌入这些图片)。

不过,我想在我的代码中强制执行不使用外部图片的政策。

一种方法是写一个正则表达式,从markdown源代码中提取图片链接,或者甚至可以通过markdown渲染器处理它,然后使用DOM解析器提取所有标签中的src属性。

但是,我很好奇是否有办法在Python-Markdown中钩入,提取所有图片链接,或者在解析过程中执行自定义代码(例如,如果链接是外部的就抛出异常)。

2 个回答

1

更新了 Python 3Python-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 = '''
![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

希望这对你有帮助!

9

一种方法是在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 = '''
![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>

撰写回答