首页 > 解决方案 > NodeJS - 读取 HTML 头部标签

问题描述

我想在我的 nodejs 应用程序中抓取一个 HTML 页面并形成一个头部标签列表。例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <script src="script.src"></script>
</head>
<body>
    ...
</body>
</html>

期望的输出:

['<meta charset="UTF-8">','<meta name="viewport" content="width=device-width, initial-scale=1.0">','<title>Document</title>', ...etc]

但是我有点卡住了,因为元标签没有“关闭”,所以它需要的不仅仅是简单的正则表达式和拆分。我想使用DOMParser,但我在节点环境中。我尝试使用xmldomnpm 包,但它只返回了一个换行符列表 ( \r\n)。

标签: htmlnode.jsweb-scrapingdomparser

解决方案


使用request npm请求您的页面,然后在您获得响应后,使用cheerio npm解析并从原始数据中获取您想要的任何内容。

注意:cheerio 的语法类似于 jQuery

 var request = require('request');
 var cheerio = require('cheerio')

app.get('/scrape',(req,res)=>{

request('---your website url to scrape here ---', function (error, response, body) {    
       var $ = cheerio.load(body.toString())
       let headContents=$('head').children().toString();
       console.log('headContents',headContents)
  });

});

推荐阅读