我有兩個問題。刮問題
我想獲得propval的價值,但是當我運行scraper時,我只是得到一個排空的字符串。 除了過濾器還是我沒有選擇正確的元素,我應該使用不同的方法 ?我試過 不同的元素,但它做同樣的事情。
我可以使用循環遍歷每一個錶行來收集所有的prop值id嗎?還是有更高效的方法?
const express = require('express');
const fs = require('fs');
const request = require('request');
const cheerio = require('cheerio');
var app = express();
app.get('/scrape', function(req, res) {
url = 'http://streak.espn.com/en/';
request(url, function(error, response, html){
if(!error) {
var $ = cheerio.load(html);
var gameQuestion, propVal;
var json = { gameQuestion : "", propVal : ""};
$('.gamequestion').each(function(){
var data = $(this)
gameQuestion = data.text();
json.gameQuestion = gameQuestion;
})
$('a#.matchupDiv').each(function() {
var data = $(this);
propVal = data.text();
json.propVal = propVal;
})
}
fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){
console.log('File successfully written! - Check your project directory for the output.json file');
})
res.send('Check your console!')
});
})
app.listen('8081')
console.log('magic happens on port 8081');
exports = module.exports = app;
<tbody>
<tr>
<td rowspan = "2" class='mg-column1 start'></td>
<td rowspan = "2" class='mg-column2 start'></td>
<td rowspan = "2" class='mg-column3 start'></td>
<div class="mg-check" propval="m57207o58439" name="matchupDiv">nbsp;</div>
可以使用'(.mg-check')。attr('propVal')''.each()'方法。 –
BC當我嘗試鏈接它們時出現錯誤 –
'$('。mg-check')'將返回一個元素數組,因爲該類有多個元素。也許更好的語法是:'$('。mg-check')。each(function(){json.propVal.push($(this).attr('propVal'))});'存儲propVals在一個數組中。這意味着您需要將'json.propVal'(和'json.gameQuestion')的初始化更改爲空數組。這樣你可以在'gameQuestion'上使用push方法,這樣你就可以得到一系列問題,而不僅僅是問題中的最後一個問題 – wlh