2017-04-12 87 views
0

我有兩個問題。刮問題

  1. 我想獲得propval的價值,但是當我運行scraper時,我只是得到一個排空的字符串。 除了過濾器還是我沒有選擇正確的元素,我應該使用不同的方法 ?我試過 不同的元素,但它做同樣的事情。

  2. 我可以使用循環遍歷每一個錶行來收集所有的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> 

回答

0

jQuery的.filter()函數採用任一的元件,一個選擇器,函數,或其它jQuery對象(http://api.jquery.com/filter/)。由於你正在向過濾器傳遞一個函數,它期望你返回一個布爾值(一個真/假值)。

你可能想要使用的是.each()函數。 (http://api.jquery.com/jquery.each/)。當你查詢一個類時,你將得到一個匹配對象的數組。 .each()將循環訪問數組,您可以執行您正在嘗試執行的操作。試一試。

已添加*****我正在查看源代碼,並沒有上課propval。您需要將您的查詢更改爲:

$('.mg-check').attr('propVal')

.mg-check沒有出現有任何孩子。你想要準確地刮擦什麼?

EDITED ***爲了得到propVals數組,試試這個:

''改變你對json.propVal的初始化[],然後...

$('.mg-check').each(function(){ json.propVal.push($(this).attr('propVal')) });

+0

可以使用'(.mg-check')。attr('propVal')''.each()'方法。 –

+0

BC當我嘗試鏈接它們時出現錯誤 –

+0

'$('。mg-check')'將返回一個元素數組,因爲該類有多個元素。也許更好的語法是:'$('。mg-check')。each(function(){json.propVal.push($(this).attr('propVal'))});'存儲propVals在一個數組中。這意味着您需要將'json.propVal'(和'json.gameQuestion')的初始化更改爲空數組。這樣你可以在'gameQuestion'上使用push方法,這樣你就可以得到一系列問題,而不僅僅是問題中的最後一個問題 – wlh