Bon*_*nch 1 html jquery web-scraping cheerio
我正在尝试查看2个html表的元素:
<table class="content">
<tbody>
<tr>
<th>head1</th>
<td>value1</td>
</tr>
<tr>
<th>head2</th>
<td>value2</td>
</tr>
</tbody>
</table>
<table class="content">
<tbody>
<tr>
<th>alpha1</th>
<td>value4</td>
</tr>
<tr>
<th>alpha2</th>
<td>value5</td>
</tr>
<tr>
<th>alpha3</th>
<td>value6</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
使用jquery选择器或cheerio,我正在尝试收集这些元素并将它们放在一个JSON对象中,其中文本元素将作为键和值作为值,因此它会像这样
{head1: 'value1',head2: 'value2', alpha1: 'value4', alpha2: 'value5', alpha3: 'value6'}
Run Code Online (Sandbox Code Playgroud)
我正在努力
$('.content).map(function(i, el) {el=$(el).find('>th').text(); return el;}).get().join(',');
Run Code Online (Sandbox Code Playgroud)
但它似乎给了我2个对象,因为2个同名的表.谢谢,谢谢
要生成具有以下结构的JSON:
[{"head1": "value1"},{"head2": "value2"},{"alpha1": "value4"},{"alpha2": "value5"}, {"alpha3": "value6"}]
Run Code Online (Sandbox Code Playgroud)
迭代表行并将对象推入数组:
function createJSON(){
var self = this;
self.thejson = [];
$('.content tr').each(function(index, value){
var k = $('th', this).text(), v = $('td', this).text();
var data = {};
data[k] = v;
self.thejson.push(data);
});
return self.thejson;
}
Run Code Online (Sandbox Code Playgroud)
编辑:操作最初将所需的JSON指定为对象数组,但后来将其更新为以下结构:
{
"head1": "value1",
"head2": "value2",
"alpha1": "value4",
"alpha2": "value5",
"alpha3": "value6"
}
Run Code Online (Sandbox Code Playgroud)
这个想法是一样的,但这次我们将数据添加到对象而不是将对象添加到数组:
function createJSON(){
var self = this;
self.thejson = {};
$('.content tr').each(function(index, value){
var k = $('th', this).text(), v = $('td', this).text();
self.thejson[k] = v;
});
return self.thejson;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4144 次 |
| 最近记录: |