HTML格式化工具

专业的HTML代码格式化工具,支持美化、压缩、标签转换等多种功能

输入HTML代码

粘贴需要格式化的HTML代码

0 字符 0 行

格式化选项

选择格式化方式

格式化类型

缩进方式

缩进大小

其他选项

格式化结果

格式化后的HTML代码

原始大小: 0 字符
格式化后: 0 字符
压缩率: 0%

内容提取

从HTML中提取特定内容

代码示例

以下是在不同编程语言中处理HTML的代码示例:

JavaScript HTML处理

// HTML压缩
function minifyHTML(html) {
    return html
        .replace(//g, '') // 移除注释
        .replace(/\s+/g, ' ') // 合并空白
        .replace(/>\s+<') // 移除标签间空白
        .replace(/\s*([<>])\s*/g, '$1') // 移除尖括号周围的空白
        .trim();
}

// HTML美化
function beautifyHTML(html, indent = '    ') {
    let formatted = '';
    let indentLevel = 0;
    let i = 0;
    
    while (i < html.length) {
        // 处理开始标签
        if (html[i] === '<' && html[i + 1] !== '/') {
            // 查找标签结束位置
            const end = html.indexOf('>', i);
            if (end === -1) break;
            
            const tag = html.substring(i, end + 1);
            
            // 检查是否是自闭合标签
            const isSelfClosing = /\/>$/.test(tag) || 
                /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)/i.test(tag.substring(1));
            
            formatted += '\n' + indent.repeat(indentLevel) + tag;
            
            if (!isSelfClosing) indentLevel++;
            i = end + 1;
        }
        // 处理结束标签
        else if (html[i] === '<' && html[i + 1] === '/') {
            indentLevel = Math.max(0, indentLevel - 1);
            const end = html.indexOf('>', i);
            if (end === -1) break;
            formatted += '\n' + indent.repeat(indentLevel) + html.substring(i, end + 1);
            i = end + 1;
        }
        // 处理文本内容
        else {
            const nextTag = html.indexOf('<', i);
            if (nextTag === -1) {
                const text = html.substring(i).trim();
                if (text) formatted += '\n' + indent.repeat(indentLevel) + text;
                break;
            }
            const text = html.substring(i, nextTag).trim();
            if (text) formatted += '\n' + indent.repeat(indentLevel) + text;
            i = nextTag;
        }
    }
    
    return formatted.trim();
}

// 提取所有链接
function extractLinks(html) {
    const linkRegex = /]+href=["']([^"']+)["'][^>]*>([^<]*)<\/a>/gi;
    const links = [];
    let match;

    while ((match = linkRegex.exec(html)) !== null) {
        links.push({
            url: match[1],
            text: match[2].trim()
        });
    }

    return links;
}

// 提取所有图片
function extractImages(html) {
    const imgRegex = /]+src=["']([^"']+)["'][^>]*>/gi;
    const images = [];
    let match;

    while ((match = imgRegex.exec(html)) !== null) {
        const altMatch = match[0].match(/alt=["']([^"']*)["']/i);
        images.push({
            src: match[1],
            alt: altMatch ? altMatch[1] : ''
        });
    }

    return images;
}

// 提取纯文本
function extractText(html) {
    // 创建临时元素
    const div = document.createElement('div');
    div.innerHTML = html;
    return div.textContent || div.innerText || '';
}

Python HTML处理

import re
from html.parser import HTMLParser

# HTML压缩
def minify_html(html):
    # 移除注释
    html = re.sub(r'', '', html)
    # 合并空白
    html = re.sub(r'\s+', ' ', html)
    # 移除标签间空白
    html = re.sub(r'>\s+<', '><', html)
    # 移除尖括号周围的空白
    html = re.sub(r'\s*([<>])\s*', r'\1', html)
    return html.strip()

# 提取所有链接
def extract_links(html):
    link_pattern = r']+href=["\']([^"\']+)["\'][^>]*>([^<]*)'
    links = re.findall(link_pattern, html, re.IGNORECASE)
    return [{'url': url, 'text': text.strip()} for url, text in links]

# 提取所有图片
def extract_images(html):
    img_pattern = r']+src=["\']([^"\']+)["\'][^>]*>'
    images = re.findall(img_pattern, html, re.IGNORECASE)

    result = []
    for img_tag in images:
        alt_match = re.search(r'alt=["\']([^"\']*)["\']', img_tag, re.IGNORECASE)
        result.append({
            'src': img_tag,
            'alt': alt_match.group(1) if alt_match else ''
        })

    return result

# 提取纯文本(使用HTMLParser)
class TextExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.text = []

    def handle_data(self, data):
        self.text.append(data)

    def get_text(self):
        return ' '.join(self.text).strip()

def extract_text(html):
    parser = TextExtractor()
    parser.feed(html)
    return parser.get_text()

# 使用BeautifulSoup处理HTML
# pip install beautifulsoup4
from bs4 import BeautifulSoup

def extract_with_bs4(html):
    soup = BeautifulSoup(html, 'html.parser')

    # 提取所有链接
    links = [{'url': a['href'], 'text': a.get_text(strip=True)}
             for a in soup.find_all('a', href=True)]

    # 提取所有图片
    images = [{'src': img['src'], 'alt': img.get('alt', '')}
              for img in soup.find_all('img', src=True)]

    # 提取文本
    text = soup.get_text(separator=' ', strip=True)

    return {
        'links': links,
        'images': images,
        'text': text
    }

Node.js HTML处理

// 使用 cheerio 处理 HTML
// npm install cheerio
const cheerio = require('cheerio');

function processHTML(html) {
    const $ = cheerio.load(html);
    
    // 提取所有链接
    const links = [];
    $('a[href]').each((i, el) => {
        links.push({
            url: $(el).attr('href'),
            text: $(el).text().trim()
        });
    });
    
    // 提取所有图片
    const images = [];
    $('img[src]').each((i, el) => {
        images.push({
            src: $(el).attr('src'),
            alt: $(el).attr('alt') || ''
        });
    });
    
    // 提取文本
    const text = $.text().trim();
    
    return {
        links,
        images,
        text
    };
}

关于HTML格式化

为什么要格式化HTML?

HTML格式化是指将HTML代码按照一定的规范进行排版和缩进,使代码更易读、易维护。良好的HTML结构可以提高开发效率,便于调试,并有助于SEO优化。

HTML压缩 vs 美化

  • HTML美化(展开格式):增加缩进、换行,使代码易于阅读和编辑。适合开发环境。
  • HTML压缩(精简格式):移除所有不必要的空白、注释,减少文件大小。适合生产环境,可以加快页面加载速度。

HTML最佳实践

  • 使用语义化标签(header、nav、main、footer等)
  • 为所有图片添加alt属性
  • 使用正确的文档类型声明( )
  • 保持标签嵌套的正确性
  • 使用小写标签名
  • 属性值使用引号
  • 避免使用过时的标签和属性

常见问题(FAQ)

Q: HTML压缩会影响SEO吗?

A: 不会。搜索引擎能够正确解析压缩后的HTML。但是,压缩可能会影响开发调试,因此建议只在生产环境使用压缩后的HTML。

Q: 应该使用双引号还是单引号?

A: HTML规范没有强制要求,但推荐使用双引号,这在XHTML中是必需的。保持代码风格一致更重要。