获取呈现的HTML输出
是否有js / npm模块从HTML获取呈现的输出(不parsingHTML)。 说例如我有以下的HTML:
<div class="st_view recipe-tab ingredients st_view_first st_view_active" style="position: absolute; left: 0px;"> <h1 class="tab-hint"> Yields: <span itemprop="recipeYield" class="tab-hint-value">2 Servings</span> </h1> <ol> <li itemprop="ingredients">1 <strong> Banana Nut Muffin Bar</strong> </li> <li itemprop="ingredients">3 tablespoons <strong>Vanilla Milkshake Protein Powder</strong> </li> <li itemprop="ingredients">1 <sup>1</sup>⁄ <sub>2</sub> tablespoons banana, mashed </li> <li itemprop="ingredients"> <sup>1</sup>⁄ <sub>2</sub> tablespoon unsweetened almond milk </li> <li itemprop="ingredients">1 teaspoon walnuts, crushed </li> <li itemprop="ingredients"> <sup>1</sup>⁄ <sub>4</sub> teaspoon banana extract </li> <li itemprop="ingredients"> <sup>1</sup>⁄ <sub>4</sub> teaspoon zero-calorie sweetener </li> <li itemprop="ingredients">Pinch of cinnamon </li> </ol> </div>
这呈现以下输出:
有无论如何访问上面的渲染线(没有实际parsing通过HTML)?
例如: var lineSix = getLineSixFromRenderedHTML(html);
编辑:我想在一个节点js服务器端环境(不使用jquery)做这个,我不想parsing的HTML通过个别元素来构造我的输出。 我只想访问渲染线(而不是HTML)。
这是你所需要的,虽然我不太确定你真正的弦是多么复杂
var str = `your-very-long-html-string`; var htmlToText = require('html-to-text'); var text = htmlToText.fromString(str, { wordwrap: 130 }); console.log(text);
结果
YIELDS: 2 SERVINGS 1. 1 Banana Nut Muffin Bar 2. 3 tablespoons Vanilla Milkshake Protein Powder 3. 1 1⁄ 2 tablespoons banana, mashed 4. 1⁄ 2 tablespoon unsweetened almond milk 5. 1 teaspoon walnuts, crushed 6. 1⁄ 4 teaspoon banana extract 7. 1⁄ 4 teaspoon zero-calorie sweetener 8. Pinch of cinnamon
你可以做到这一点,如果你给每一个li标签的id,然后使用jquery获取标签内的html。
例如:
<li itemprop="ingredients" id="ingredient_6">1 <sup>1</sup>⁄ <sub>2</sub> tablespoons banana, mashed </li>
然后用jQuery:
var lineSix = $('#ingredient_6').html();
OP要求这个例子。
它使用jQuery,主要是为了简单,如果你不想要jQuery,你将不得不看看他们的源代码,并重新创build我猜的function。 请注意,如果在这里运行,你会得到一个轻微的诡计行为,因为跑步者将脚本和样式添加到错误的地方。
console.log($("html").find("*").toArray()[0]);
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div> hello </div> </body> </html>
您可以使用.innerHTML
和.outerHTML
属性的组合。 使用您的示例HTML,您可以这样做:
var list = document.querySelector('ol'); list.innerHTML; list.outerHTML;
List返回一个DOM节点,它有一个children
属性。 要访问<ol>
列表中的第六项,您可以使用:
var 6thChild = list.children[5]; 6thChild.innerHTML; 6thChild.outerHTML;