kindedit編輯器和xxs攻擊防護(BeautifulSoup)的簡單使用


一、kindedit編輯器

就是上面這樣的編輯輸入文本的一個編輯器

這也是一個插件。那么怎么用呢?

1、下載:百度kindedit

2、引入:

    <script src="/static/kindeditor/kindeditor-all.js"></script>

 

3、看官方提供的文檔

在addarticle.html中

    <script>
        {#        KindEditor編輯器的使用#}
        KindEditor.ready(function (K) {
            window.editor = K.create('#id_content', {
                {#                    width:"1030px"#}
                width: "90%",
                height: "500px",
                resizeType: 0,//編輯器不拉伸
                uploadJson: "/uploadFile/",  //上傳圖片路徑
                {#                    items:['preview', 'print', 'template', 'code', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',]#}
                //items:你可以篩選你自己想要的
                extraFileUploadParams: {     #解決forbidden
                    csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
                }
            });
        });
    </script>

 

當你把編輯器插入好的時候,你看似都可以設置大小,字體變粗等。。但是當你上傳圖片的時候就會想下面一樣

這時候就需要 uploadJson: "/uploadFile/",  這個參數了。

url.py

 url(r'^uploadFile/$', views.uploadFile),

 

views.py

def uploadFile(request):
    '''上傳圖片路徑'''
    print(request.path)  #返回的是當前請求的路徑
    print(request.FILES)  #<MultiValueDict: {'imgFile': [<InMemoryUploadedFile: 44643.gif (image/gif)>]}>
    file_obj = request.FILES.get("imgFile")  #得到用戶上傳的文件對象
    filename = file_obj.name  #那到文件的文件名
    path = os.path.join(settings.MEDIA_ROOT,"upload_article_img",filename) #拼接一個路徑吧文件保存進去,一般上傳文件的路徑保存在media中
    print("======",path)
    with open(path,"wb") as f:#吧文件保存在本地      
        for line in file_obj:     #也可以for i in chunks()   不是一行一行的讀,而是有具體的大小64*2**10
            f.write(line)
   response
= { "error":0, "url":"/media/upload_article_img/"+filename+"/" #前端圖片文件預覽 } return HttpResponse(json.dumps(response)) #需要注意的是上傳文件返回的是一個json字符串

 

二、XSS攻擊防護:

BeautifulSoup:是python的一個庫,查你想要的數據的,但是只是針對標簽字符串。主要用於從網頁爬取數據 

1、首先需要知道的一些基礎知識

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The Dormouse's story
   </b>
  </p>
  <div id="d1" class="d1">
    <b>
    The Dormouse's story2
    </b></div>
  <p class="story">
   Once upon a time there were three little sisters; and their names were
   <a class="sister0" href="http://example.com/elsie" id="link1">
    Elsie
   </a>
   ,
   <a class="sister1" href="http://example.com/lacie" id="link2">
    Lacie
   </a>
   and
   <a class="sister2" href="http://example.com/tillie" id="link3">
    Tillie
   </a>
   ;
and they lived at the bottom of a well.
  </p>
   <script>alert(1234)</script>
  <p class="story sister2">
   ...
  </p>
 </body>
</html>
"""
# 第一步:實例化對象
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,"html.parser")
# 第二步:美化
print(soup.prettify())
# 第三步:查找標簽
print(soup.a)  #只能找到符合條件的第一個標簽
print(soup.find("a")) #只能找到符合條件的第一個標簽
print(soup.find_all("a"))  #找到所有的a標簽
print(soup.a["class"])  #找到a標簽的class屬性
print(soup.find_all(name="a"))#找所有標簽名是a標簽的
print(soup.find_all(attrs={"class":"sister1"}))#找屬性是class=sister1的
print(soup.find_all(name="a",attrs={"class":"sister1"}))#找a標簽並且屬性是class=sister1的

# ===========================
for ele_a in soup.find_all("a"):
    print(ele_a.attrs)  #找出a標簽的所有的屬性
    print(ele_a["href"])  #找出所有的a標簽的href屬性
    print(ele_a["class"])  #找出所有的a標簽的class屬性

for ele_a in soup.find_all("a"):
    print(ele_a.attrs)  #找出a標簽的所有屬性
    del ele_a["class"]  #刪除a標簽的class屬性
#
for ele_a in soup.find_all("a"):
    print(ele_a)  #找出a標簽


for ele in soup.find_all():
    if ele.attrs:
        '''如果有屬性'''
        if ele.attrs.get("class"):
            '''如果得到class屬性'''
            print(ele.attrs)
            del ele["class"]
print(soup)


for ele_a in soup.find_all("script"):    #soup是整個文檔對象,循環整個文檔的所有的script標簽
    print(ele_a.string)  #所有a標簽的文本
    print(ele_a.text)    #所有a標簽的文本
    ele_a.string.replace_with("//別瞎玩")  #替換a標簽的文本
print(soup)

 四個對象:

  1、comment對象:注釋對象

  2、Tag標簽對象:相當於html中的一個標簽對象

  3、BeautifulSoup對象:相當於整個文檔對象(Dom對象)

  4、Navigablefetry文本對象

下面我們來具體應用一下:xss攻擊防護。吧一些不安全的給刪除或者替換了

def filter_xss(html_str):
    valid_tag_list = ["p", "div", "a", "img", "html", "body", "br", "strong", "b"]    #有效標簽列表

    valid_dict = {"img":["src","alt"],"p": ["id", "class"], "div": ["id", "class"]}    #有效屬性列表

    from bs4 import BeautifulSoup

    soup = BeautifulSoup(html_str, "html.parser")  # soup  ----->  document

    ######### 改成dict
    for ele in soup.find_all():
        # 過濾非法標簽
        if ele.name not in valid_dict:
            ele.decompose()
        # 過濾非法屬性

        else:
            attrs = ele.attrs  # p {"id":12,"class":"d1","egon":"dog"}
            l = []
            for k in attrs:
                if k not in valid_dict[ele.name]:
                    l.append(k)

            for i in l:
                del attrs[i]

    print(soup)

    return soup.decode()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM