You need to enable JavaScript to run this app. 如何使用cheerio将HTML中的head标签替换为自定义代码
优惠活动
大模型
产品
解决方案
定价
更多

如何使用cheerio将HTML中的head标签替换为自定义代码

使用Cheerio替换HTML中head标签的操作方法

  • 先安装cheerio依赖(已安装可跳过):
    npm install cheerio
    
  • 核心实现代码示例:
    const cheerio = require('cheerio')
    
    // 你的原始HTML内容
    const rawHtml = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>Example</title>
    </head>
    <body>
    Example html doc......
    </body>
    </html>
    `
    
    // 你自行准备的完整head代码
    const customHead = `
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>我的自定义标题</title>
      <link rel="stylesheet" href="./static.css">
      <script src="./common.js"></script>
    </head>
    `
    
    // 加载HTML并执行替换
    const $ = cheerio.load(rawHtml)
    $('head').replaceWith(customHead)
    
    // 输出处理后的完整HTML
    const resultHtml = $.html()
    console.log(resultHtml)
    
  • 补充说明:如果你只需要替换head标签内部的内容,不需要替换head标签本身,可以不用写完整的<head>包裹,直接用$('head').html(自定义内部内容)即可,效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 10:15:09