from bs4 import BeautifulSoup

class XSSFilter(object):
    __instance = None

    def __init__(self):
        # XSS白名单
        self.valid_tags = {
            "font": ['color', 'size', 'face', 'style'],
            'b': [],
            'div': [],
            "span": [],

    def __new__(cls, *args, **kwargs):
        :param cls:
        :param args:
        :param kwargs:
        if not cls.__instance:
            obj = object.__new__(cls, *args, **kwargs)
            cls.__instance = obj
        return cls.__instance

    def process(self, content):
        soup = BeautifulSoup(content, 'html.parser')
        # 遍历所有HTML标签
        for tag in soup.find_all(recursive=True):
            # 判断标签名是否在白名单中
            if not in self.valid_tags:
                tag.hidden = True
                if not in ['html', 'body']:
                    tag.hidden = True
            # 当前标签的所有属性白名单
            attr_rules = self.valid_tags[]
            keys = list(tag.attrs.keys())
            for key in keys:
                if key not in attr_rules:
                    del tag[key]

        return soup.decode()

if __name__ == '__main__':
    html = """<p class="title">
                        <b>The Dormouse's story</b>
                    <p class="story">
                        <div name='root'>
                            Once upon a time there were three little sisters; and their names were
                            <a  class="sister" id="link2">Lacie</a> and
                            <a  class="sister" id="link3">Tilffffffffffffflie</a>;
                            and they lived at the bottom of a well.
                    <p class="story">...</p>"""

    obj = XSSFilter()
    v = obj.process(html)

未经允许不得转载:梦栈技术园 » bs4过滤的方式防xss跨站脚本

赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址