html - 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
,但我在节点环境中。我尝试使用xmldom
npm 包,但它只返回了一个换行符列表 ( \r\n
)。
解决方案
使用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)
});
});
推荐阅读
- rasa-nlu - 无法在 rasa 中捕获插槽颜色值
- python - Python Pandas 从 Dataframe 中获取单个值
- java - 有没有办法在 Android Studio 中教 java-> kotlin 转换器在转换 findViewById 时不使用 `as` 运算符?
- javascript - 如何使用 document.getElementById("id") 更改文本的值或选择下拉值
- php - 如何通过 PHP CURL 连接到 amazon-lightsail 并列出所有实例?
- java - 如何为 Jenkins 提供依赖 JAR 以构建 Maven 项目?
- java - 找到连接图的最低成本的替代方法
- sql - 在mysql中将varchar转换为数字
- android - 编辑 Exif 数据后图像仍然旋转
- java - 如何创建接口 Comparable 的对象