我编写了从某些网页解析大量单词(innerHTML)的代码。
我想直接将数据插入到json文件中..
这是我的js代码...
var words = [];
var casper = require('casper').create();
function getWords() {
var words = document.querySelectorAll('td.subject a');
return Array.prototype.map.call(words, function(e) {
return e.innerHTML;
});
}
casper.start('http://www.todayhumor.co.kr/board/list.php?table=bestofbest', function() {
words = this.evaluate(getWords);
});
for (var i=2; i <=5; i++) {
casper.thenOpen('http://www.todayhumor.co.kr/board/list.php?table=bestofbest&page='+i, function() {
words = words.concat(this.evaluate(getWords));
});
}
casper.run(function() {
// echo results in some pretty fashion
this.echo(words.length + ' links found:').exit();
this.echo(words.join('\n')).exit();
});
和
我通过这样的终端运行此代码!
username@wow:~/workspace/app/assets/javascripts $ casperjs application.js
结果是(例如)
150 words found:
apple
banana
melon
kiwi
citrus
watermelon
passionfruit
mango
orange
...
所以我想将此数据插入到我的 json 文件的“word”部分中(下面是 json 的示例代码)
并自动添加其他列(“type”:“fruit”和“spell”:)
{ "my_initial_words": [
{
"type": "fruit",
"word": "apple",
"spell": "ap"
},
{
"type": "fruit",
"word": "banana",
"spell": "ba"
},
{
"type": "fruit",
"word": "melon",
"spell": "me"
}
]
}
----------------------------------------------------------------------------
感谢您添加更多答案!... 但我不知道应该把这些代码放在哪里
你能再告诉我一次吗...你给我的哪段代码执行“将结果保存到 JSON 文件?”因为我必须像这样读取 seeds.rb
文件中的 json 文件(makeyourap.json)
require 'json'
file = File.open(Rails.root.join('db','makeyourap.json'))
contents = file.read
json = ActiveSupport::JSON.decode(contents)["my_initial_words"]
最佳答案
那么,类似这样的事情吗?
function makeTypeObject(name, type) {
return {
name: name,
type: type,
spell: name.substr(0,2)
};
}
var wordDesc = words.map(function (word) {
return makeTypeObject(word, "fruit");
});
var finalObject = {
my_initial_words: wordDesc
};
var jsonString = JSON.stringify(finalObject);
// if you want prettyprint, try JSON.stringify(finalObject, null, "\t");
我希望这会有所帮助。
关于javascript - 通过casperjs爬取后如何在json中插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32360348/