高效提取html字符串中的特定数据
本文介绍如何从一段HTML字符串中提取特定结构的数据。假设HTML包含多个
例如,我们有如下HTML字符串:
<div class="template_content" data-template="template1"> ...<div>内容1aaa</div><div>内容1bbb</div>... </div> <h3>标题1</h3> <div class="template_content" data-template="template2"> <p>内容2</p> </div> <h3>标题2</h3> <div class="template_content" data-template="template3"> <p>内容3</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p> </div> <h3>标题3</h3> <div class="template_content" data-template="template4"> <p>内容4</p> </div>
我们需要提取以下格式的数据:
{ "data-template": "(提取内容1)", "content": "(提取内容2)" }
其中,“提取内容1”对应data-template属性值,“提取内容2”对应
虽然可以使用正则表达式,但为了更稳健地处理HTML内容,建议使用DOM解析器。以下JavaScript代码演示了如何使用DOMParser实现这一目标:
let html = ` <div class="template_content" data-template="template1"> ...<div>内容1aaa</div><div>内容1bbb</div>... </div> <h3>标题1</h3> <div class="template_content" data-template="template2"> <p>内容2</p> </div> <h3>标题2</h3> <div class="template_content" data-template="template3"> <p>内容3</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p> </div> <h3>标题3</h3> <div class="template_content" data-template="template4"> <p>内容4</p> </div> `; const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); const divs = doc.querySelectorAll('div.template_content'); const extractedData = []; divs.forEach(div => { const template = div.getAttribute('data-template'); const content = div.innerHTML; extractedData.push({ "data-template": template, "content": content }); }); console.log(extractedData);
这段代码首先使用DOMParser将HTML字符串解析成DOM树,然后使用querySelectorAll选择所有具有class="template_content"的
以上就是如何从HTML字符串中提取特定div元素的data-template属性值及其内容?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号