2017-02-20 68 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;