You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Curl抓取网页并保留HTML元素的正确缩进格式

解决curl抓取HTML无缩进的方法

这种压缩成一行的HTML确实看着糟心,我来给你分享几个实用的解决办法,不管是用命令行工具还是你提到的PHP/Node.js栈都能搞定:

一、命令行工具配合curl(最简便)

如果你不想写代码,直接用系统自带或易安装的命令行工具就能快速解决:

1. 使用tidy

tidy是专门用于清理和格式化HTML/XML的工具,大部分Linux发行版默认自带,macOS可以通过brew install tidy安装。执行命令:

curl somewebsite.com/somepage | tidy -i -q -wrap 0 > formatted.html

参数说明:

  • -i:开启自动缩进
  • -q:安静模式,屏蔽冗余警告信息
  • -wrap 0:禁止自动换行,避免长标签被强制拆分

2. 使用xmllint

xmllint是libxml2工具集的一部分,多数系统默认预装。处理HTML时记得加上--html参数,避免XML解析报错:

curl somewebsite.com/somepage | xmllint --html --format - > formatted.html

如果遇到不规范HTML解析失败的情况,可以尝试添加--html --xmlout参数提升兼容性。

二、PHP解决方案

如果你熟悉PHP,写个简单脚本就能实现格式化:

<?php
// 替换为目标抓取URL
$targetUrl = 'https://somewebsite.com/somepage';
$rawHtml = file_get_contents($targetUrl);

// 初始化DOMDocument
$dom = new DOMDocument();
// 关闭libxml错误提示,兼容不规范HTML
libxml_use_internal_errors(true);
$dom->loadHTML($rawHtml);
libxml_clear_errors();

// 开启格式化输出
$dom->formatOutput = true;
// 保存格式化后的HTML到文件
file_put_contents('formatted.html', $dom->saveHTML());

echo 'HTML格式化完成,已保存到formatted.html';
?>

运行脚本后,DOMDocument会自动处理标签嵌套,生成带正确缩进的HTML文件。

三、Node.js解决方案

Node.js有很多轻量库可以处理HTML格式化,这里推荐两种常用方式:

1. 使用cheerio(轻量快速)

先安装cheerio:

npm install cheerio

然后编写脚本:

const cheerio = require('cheerio');
const fs = require('fs');
const https = require('https');

const targetUrl = 'https://somewebsite.com/somepage';

// 发起请求获取原始HTML
https.get(targetUrl, (response) => {
  let rawHtml = '';
  response.on('data', chunk => rawHtml += chunk);
  response.on('end', () => {
    // 加载HTML到cheerio
    const $ = cheerio.load(rawHtml, { decodeEntities: true });
    // 格式化输出,指定2个空格作为缩进
    const formattedHtml = $.html({ prettyPrint: true, indent: '  ', newline: '\n' });
    // 写入文件
    fs.writeFileSync('formatted.html', formattedHtml);
    console.log('格式化完成,文件已保存');
  });
}).on('error', err => {
  console.error('请求失败:', err.message);
});

2. 使用prettier(格式化效果更统一)

prettier是知名的代码格式化工具,对HTML的支持成熟,风格更规范:

先安装prettier:

npm install prettier

然后编写脚本:

const prettier = require('prettier');
const fs = require('fs');
const https = require('https');

const targetUrl = 'https://somewebsite.com/somepage';

https.get(targetUrl, (response) => {
  let rawHtml = '';
  response.on('data', chunk => rawHtml += chunk);
  response.on('end', async () => {
    try {
      // 用prettier格式化HTML
      const formattedHtml = await prettier.format(rawHtml, {
        parser: 'html',
        tabWidth: 2,
        printWidth: 120,
        singleQuote: false
      });
      fs.writeFileSync('formatted.html', formattedHtml);
      console.log('格式化完成!');
    } catch (err) {
      console.error('格式化失败:', err.message);
    }
  });
}).on('error', err => {
  console.error('请求出错:', err.message);
});

这些方法都能轻松解决HTML无缩进的问题,选你顺手的工具就行~

内容的提问来源于stack exchange,提问作者Mohammed Khurram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:49:07