2017-04-19 37 views
1

我刚开始学习刮网站。刮网站|我如何创建JSON文件?

我刮的网站有一个主要的类“内容”。 Content div内部是文章,文章的标题位于<h2>标签内。

我已经想出了用以下代码引用标题。现在我想将所有标题保存在JSON文件中。如何为每个标题创建对象。很明显,我的代码只是用obj代替标题,每次迭代。

var title, date, img_url, permalink; 
var obj = { title : "", date : "", img_url : "", permalink : ""}; 

     // ======== Extracting Title ================ 
     $('#Content').filter(function(){ 
      var data = $(this); 
      let headers = data.find('h2'); 

      headers.each(function (i, el) { 
       obj.title = $(el).text(); 
      }) 
     }) 

回答

2

如果你想类似{title: "Some title"}每个<h2>元素对象的数组,那么你可以简单地使用

const headerObjects = Array.from(document.querySelectorAll('#Content h2')).map(h2 => ({ 
 
    title: h2.textContent 
 
})) 
 

 
console.info(headerObjects)
<div id="Content"> 
 
<h2>Title 1</h2> 
 
<p>Here's some text</p> 
 
<h2>Title 2</h2> 
 
<p>Some more text</p> 
 
<h2>Last title</h2> 
 
<p>One more paragraph</p> 
 
</div>

参考:

0

尝试下面的代码,。在这个代码当您单击「创建文件」按钮,它会创建下载link.That链接导致下载JSON文件格式化O/p。

var json = []; 
 
$("h2").each(function(i) { 
 
    var title = $(this).html(); 
 
    item = {}; 
 
    item ["title"] = title; 
 
    json.push(item); 
 
}); 
 

 
(function() { 
 
    var textFile = null, 
 
     makeTextFile = function (text) { 
 
     var data = new Blob([text], {type: 'application/json'}); 
 
     if (textFile !== null) { 
 
      window.URL.revokeObjectURL(textFile); 
 
     } 
 
     textFile = window.URL.createObjectURL(data); 
 
     return textFile; 
 
     }; 
 
    create.addEventListener('click', function() { 
 
    var link = document.getElementById('downloadlink'); 
 
    link.href = makeTextFile(JSON.stringify(json, null, 4)); 
 
    link.style.display = 'block'; 
 
    }, false); 
 
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="Content"> 
 
    <h2>Title 1</h2> 
 
    <p>Here's some text</p> 
 
    <h2>Title 2</h2> 
 
    <p>Some more text</p> 
 
    <h2>Last title</h2> 
 
    <p>One more paragraph</p> 
 
</div> 
 
<button id="create">Create file</button> 
 
<a download="info.txt" id="downloadlink" style="display: none">Download</a>

这里是工作的jsfiddle:https://jsfiddle.net/o1kvk63o/

我想应该是可以帮助你