繁体   English   中英

使用python-markdown检查图片网址

[英]Check image urls using python-markdown

在我正在创建的网站上,我正在使用Python-Markdown格式化新闻帖子。 为了避免死链接和HTTP-content-on-HTTPS-page问题的问题,我要求编辑将所有图像上传到网站然后嵌入它们(我使用的是降价编辑器,我已修补它以便于嵌入那些使用标准降价语法的图像)。

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

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

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

一种方法是在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>

更新了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

希望它有用!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM