2017-02-20 74 views
1

是否有js/npm模块从HTML获取呈现的输出(不解析HTML)。例如说我有以下HTML:获取呈现的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> 

这使得下面的输出:

enter image description here

反正是有访问以上(不通过HTML实际上解析)渲染线?

如:var lineSix = getLineSixFromRenderedHTML(html);

编辑:我想这样做在节点JS服务器端环境(不使用jQuery),我不想来解析HTML要经过各个元素来构造我的输出。我只想访问渲染线(而不是HTML)。

+0

你可以给该行分配一个'id'并使用它在javasript中进行选择吗? – user2027202827

+0

你是什么意思?你想在你的html文档中获得第六个元素吗?因为你可以用一些简单的javascript做到这一点:https://www.w3schools.com/js/js_htmldom_document.asp –

+0

@SimonHyll一般来说,请不要使用w3schools作为参考,使用MDN(例如https:// developer .mozilla.org/en-US/docs/Web/API/Document)或其他更有信誉的地方。 – mscdex

回答

1

This是你所需要的,虽然我不是很确定你真正的字符串是多么复杂

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 
0

你可以做到这一点,如果你给每一个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();

0

的任择议定书要求的这个例子。

它使用jQuery,主要是为了简单,如果你不想jQuery你必须看他们的源代码并重新创建我猜的功能。请注意,如果在这里运行,您将会看到一些轻微的行为,因为跑步者在错误的位置添加了脚本和样式。

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>

0

您可以使用.innerHTML.outerHTML属性的组合。使用您的示例HTML,你可以这样做:

var list = document.querySelector('ol'); 
list.innerHTML; 
list.outerHTML; 

列表返回一个DOM节点,其中有一个children属性。要访问<ol>列表中的第六项,你可以使用:

var 6thChild = list.children[5]; 
6thChild.innerHTML; 
6thChild.outerHTML;