簡體   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