Node.js 刮擦问题
我有两个问题Node.js 刮擦问题,node.js,web-scraping,Node.js,Web Scraping,我有两个问题 我试图得到propval的值,但是当我运行scraper时,我只得到一个清空字符串我应该使用不同的方法吗 除了过滤器还是我没有选择正确的元素?我已经尝试过了 不同的元素,但它做相同的事情 我是否可以使用循环遍历每个表行来收集所有属性值ID,或者是否有更有效的方法 const express=require('express'); 常数fs=要求('fs'); const request=require('request'); const cheerio=需要(“cheerio”);
const express=require('express');
常数fs=要求('fs');
const request=require('request');
const cheerio=需要(“cheerio”);
var-app=express();
app.get('/scrape',函数(req,res){
url='1〕http://streak.espn.com/en/';
请求(url、函数(错误、响应、html){
如果(!错误){
var$=cheerio.load(html);
问题本身;
var json={gameQuestion:,propVal:};
$('.gamequestion')。每个(函数(){
变量数据=$(此)
gameQuestion=data.text();
json.gameQuestion=gameQuestion;
})
$('a#.matchupDiv')。每个(函数(){
var数据=$(此);
propVal=data.text();
json.propVal=propVal;
})
}
fs.writeFile('output.json',json.stringify(json,null,4),函数(err){
log('File successfully writed!-检查项目目录中的output.json文件');
})
res.send('检查控制台!')
});
})
应用程序监听('8081')
log('magic cours on port 8081');
导出=模块。导出=应用程序;
nbsp;
jQuery.filter()
函数接受元素、选择器、函数或另一个jQuery对象()。由于要将函数传递到过滤器中,因此它希望您返回布尔值(真/假值)
您可能想要使用的是.each()
函数。(). 当您查询一个类时,您将返回一个匹配对象的数组.each()
将在数组中循环,您可以在数组中执行您试图执行的操作。试试看
添加了******我正在查看源代码,没有类propval
。您需要将查询更改为:
$('.mg check').attr('propVal')
但是.mg check
似乎没有孩子。你到底想刮什么
已编辑***若要获取属性数组,请尝试以下操作:
将json.propVal
的初始化从'
更改为[]
,然后
$('.mg check').each(function(){json.propVal.push($(this.attr('propVal')))})
您可以在$('.mg check').attr('propVal')
上使用.each()
方法吗?$('.mg check')
将返回一个元素数组,因为该类有多个元素。也许更好的语法是:$('.mg check').each(function(){json.propVal.push($(this.attr('propVal'))})
将属性存储在数组中。这意味着您需要将json.propVal
(以及json.gameQuestion
)的初始化更改为空数组。这样你就可以在你的gameQuestion
上使用push方法,这样你就有了一系列的问题,而不仅仅是最后一个问题
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>