我正在尝试使用nodejs抓取一个网站,它可以在不需要任何身份验证的网站上完美运行。但每当我尝试使用需要用户名和密码的表单来抓取网站时,我只会从身份验证页面获取HTML(也就是说,如果您在身份验证页面上单击“查看页面源”,那就是HTML I得到)。我可以使用curl
获得所需的HTMLcurl -d "username=myuser&password=mypw&submit=Login" URL
这是我的代码......
var express = require('express');
var fs = require('fs'); //access to file system
var request = require('request');
var cheerio = require('cheerio');
var app = express();
app.get('/scrape', function(req, res){
url = 'myURL'
request(url, function(error, response, html){
// check errors
if(!error){
// Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
var $ = cheerio.load(html);
var title, release, rating;
var json = { title : "", release : "", rating : ""};
$('.span8 b').filter(function(){
// Let's store the data we filter into a variable so we can easily see what's going on.
var data = $(this);
title = data.first().text();
release = data.text();
json.title = title;
json.release = release;
})
}
else{
console.log("Error occurred: " + error);
}
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;
我试过以下......
var request = require('request',
username:'myuser',
password:'mypw');
这只返回身份验证页面的HTML
request({form: {username:myuser, password:mypw, submit:Login}, url: myURL}, function(error, response, html){
...
...
...
}
这也只是返回身份验证页面的HTML
所以我的问题是如何使用nodejs实现这一目标?
答案 0 :(得分:2)
你不应该使用.get但.post并将post param(用户名和密码)放入你的电话中
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: url,
body: "username=myuser&password=mypw&submit=Login"
}, function(error, response, html){
//do your parsing...
var $ = cheerio.load(html)
});