首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python-markdown检查图像urls

使用python-markdown检查图像urls
EN

Stack Overflow用户
提问于 2011-05-09 05:33:31
回答 2查看 2.8K关注 0票数 7

在我创建的一个网站上,我使用Python-Markdown来格式化新闻帖子。为了避免死链接和HTTP-content-on-HTTPS-page的问题,我要求编辑器将所有图片上传到站点,然后嵌入它们(我使用的是一个标记编辑器,我已经对其打了补丁,以便使用标准标记语法轻松嵌入这些图像)。

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

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-12 07:48:27

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

代码语言:javascript
复制
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

输出:

代码语言:javascript
复制
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>
票数 9
EN

Stack Overflow用户

发布于 2019-02-28 15:40:38

使用Python 3Python-Mardown 3更新

代码语言:javascript
复制
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

希望它是有用的!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5930542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档