如何用HTML编辑微信公众号,正常的网页HTML转化为内联样式的代码解决方案(jackson) - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 公众号相关 >

如何用HTML编辑微信公众号,正常的网页HTML转化为内联样式的代码解决方案(jackson)

发表时间:2020-10-19

发布人:葵宇科技

浏览次数:124

这段时间需要为公司编辑公众号,需要做一些效果漂亮的布局(图片,按钮,标题),但是默认微信官方并不能用原生的HTML编写公众号,所以需要借助第三方来编辑,壹伴还不错,可以直接把html 源代码放到微信公众号网页里。但是微信公众号内的HTML是没有像原生那样,有style标签的,只有包含在body标签里面的代码。而且body标签里面的代码样式是内联样式,这个还特意查看了网页链接的公众号,进行调试,发现确实只能是内联样式,(PS:可能更容易让用户图形化操作吧)。内联样式看着维护很难,很难去区分那个标签是什么作用的。

解决方法:所以可以用python(PS:或者其他代码,例如nodejs,个人喜欢python的风格,write less code do more thing)来读取一个html文件,然后提取style标签里面的内容 和 body标签里面的内容,再进行类型匹配,替代为内联样式,下面是python的源代码:

import sys

def is_space(s):
    return s=='\r' or s=='\n' or s=='\t' or s==' '

class ConvertInnerStyle:
    """this class is to convert the inner style into the inline style
       generate the html code which only contain the source code within the body
       it could assist the people who want to make the customize web page in the wechat subscription"""

    def __init__(self,origin):
        """make the constructor to be clear"""
        self.total_content=''
        self.style_dict={}
        self._fg_init(origin)

    def _fg_init(self,origin):
        """initialize the resouces that we provided """
        f=open(origin,'r',encoding="UTF-8")
        self.totalContent=f.read()
        f.close()
        self._process_style()

    def _fg_find_style(self,tag):
        """this is the method that can generate the substring which match the tag name of the html"""
        preffix='<'+tag+'>'
        suffix=r'</'+tag+'>'
        s=self.totalContent.find(preffix)
        e=self.totalContent.find(suffix)
        return self.totalContent[s+len(preffix)-1:e]

    def _process_style(self):
        """process the source code within the style tag ,generate the content which match the class name,(optional it can process the multiple classes which has the same styles)"""
        #get the source code within the style tag of the html
        inner_styles=self._fg_find_style('style')
        #print(inner_styles)
        #for loop that find the index of the } character
        end_index=inner_styles.find('}')
        print(end_index)
        while end_index!=-1:
            #get the substring of the single styles block
            #which contain .xxx{xxxx}   .xxx,.yyy,.uuu {xxx;xxxx;}
            single_styles=inner_styles[:end_index+1] #because the end_index is the forward element of }
            print(single_styles)
            #first find the index of {
            index=single_styles.find('{')
            ii=index-1
            #the variable to check whether it is the last class before the style block 
            is_valid=True

            class_name=''
            class_name_list=[]
            #from the end to the start loop through each charater find the class name list which can contain at least one class 
            while ii>=0:
                #if it is the space skip it 
                if is_space(single_styles[ii]):
                    ii-=1
                    continue
                c=single_styles[ii]
                if c==',':
                    is_valid=True
                    ii-=1
                    continue
                if is_valid:
                    if c=='.':
                        is_valid=False
                        #because this is the reverse class name so make it forward 
                        l=list(class_name)
                        l.reverse()
                        class_name=''.join(l)
                        class_name_list.append(class_name)
                        #empty the class name in order to reuse next loop
                        class_name=''
                    else:
                        class_name=class_name+c
                ii-=1
            #find the style block and strip the empty the \r\n charater
            style_block=single_styles[index+1:end_index]
            style_block=style_block.strip().replace('\r','').replace('\n','')
            #put the element of the class name list to the dictionary
            for tmp in class_name_list:
                self.style_dict[tmp]=style_block
            inner_styles=inner_styles[end_index+1:]
            end_index=inner_styles.find('}')

        for key in self.style_dict:
            print(key+' : '+self.style_dict[key])
    def generate(self,filename):
        #find the body 
        body=self._fg_find_style('body')
        for key in self.style_dict:
            body=body.replace('class="'+key+'"','style="'+self.style_dict[key]+'"')
        f=open(filename,'w',encoding='UTF-8')
        f.write(body)
        f.close()


def main():
    t=ConvertInnerStyle(str(sys.argv[1]))
    t.generate(str(sys.argv[2]))



if __name__ == "__main__":
    main()

使用方法:

1、通过命令行工具 python converter.py 需要转换的文件 最后生成的内联样式文件

这个工具还不支持跳过注释,有兴趣的同学可以自己去修正

.header .hr,
.header .content-wrap .content,
.header .content-wrap .icon,
.header,
.header .content-wrap {
width: 100%;
height: 40px;
display: flex;
align-items: flex-end;
justify-content: flex-start;
}

原始html里面的内部样式

content-wrap : width: 100%; height: 40px; display: flex; align-items: flex-end; justify-content: flex-start;
header : width: 100%; height: 40px; display: flex; align-items: flex-end; justify-content: flex-start;
icon : width: 100%; height: 40px; display: flex; align-items: flex-end; justify-content: flex-start;
hr : width: 100%; height: 40px; display: flex; align-items: flex-end; justify-content: flex-start;

通过python代码提取的对应类名 : 样式的字典

相关案例查看更多